java Response json out of order

Asked

Viewed 268 times

1

Guys I’m making a java API to be consumed by Excel. I’m making a bank select by bringing the columns in the right order, but when it arrives in Excel it arrives in a half crazy order.

I also made a method with:

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

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

has some way of doing the

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

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

1 answer

1

The order of methods in the Class.forName("className").getDeclaredMethods(); is not well defined. See this in 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 ordered in any particular order.

Therefore, you cannot rely on the order that this will bring the methods. Therefore, the best way is to order them explicitly by some well-defined criterion. The method name would be an initial idea, but since there may be overloaded methods (with the same name), then one can use the 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;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.