java response json out of order

1

I'm doing an API in java to be consumed by Excel. I'm doing a select from the bank bringing the columns in the right order, but when it arrives in Excel comes in a crazy order.

I also made a method with:

Class.forName("className").getDeclaredMethods.getName();

To get the names of the "get" methods of this entity class (eg, Person, Client) and these names are coming out of order as well. They are coming in the same order as the columns in json.

have some way to do the

Class.forName("className").getDeclaredMethods.getName();

maintaining the order of the methods of the class? and keep the select order in json?

    
asked by anonymous 24.08.2017 / 22:25

1 answer

1

The order of methods in Class.forName("className").getDeclaredMethods(); is not well defined. Check this out at javadoc :

  

The elements in the returned array are not sorted and are not in any particular order.

Translating:

  

The elements in the returned array are not sorted in any particular order.

So you can not trust the order this will bring the methods. Therefore, the best way is to order them explicitly by some well-defined criteria. The method name would be an initial idea, but since there might be overloaded methods (with the same name), then you can use toGenericString() to differentiate them:

public static List<Method> listMethods(Class<?> someClass) {
    List<Method> m = Arrays.asList(someClass.getDeclaredMethods());
    m.sort((m1, m2) -> {
        int c = m1.getName().compareTo(m2.getName());
        if (c != 0) return c;
        return m1.toGenericString().compareTo(m2.toGenericString());
    });
    return m;
}
    
24.08.2017 / 22:37