mardi 23 juillet 2019

Is it possible to get all methods of a class, in the correct order? [duplicate]

This question already has an answer here:

I'm trying to retrieve a list of methods inside a specific class, but it has to be in order. The second part is where I'm stuck and uncertain if it's even possible.

This is the method that retrieves the list:

public static ArrayList<Method> getAllMethods (MyClass myClass) {
    ArrayList<Method> methods = new ArrayList<Method>();
    Class c = myClass.getClass();
    while (c != Object.class) {
        Collections.addAll(methods, ClassReflection.getDeclaredMethods(c));
        c = c.getSuperclass();
    }
    return methods;
}

The result is that the list contains all the methods in a what seems to be random order. For my program that's very inconvenient. Is it possible to do this in a simple way? The only way I thought of was adding annotations and order each method by giving it a number. However, that seems like a lot of hassle for what I'm trying to achieve and I don't want to do it this way.

EDIT: I use the retrieved methods to get the annotations that belong to them. Next I display these annotations on screen in my game, because the methods are basically in-game commands. The commands are written in a logical order and some commands are grouped together so they need to be displayed next to each other and in the correct order. Here is how I display the annotation values:

@Command(description = "Shows all commands and their usages")
public void help() {
    for(Method command : Util.getAllMethods(this)) {
        Annotation anno = command.getDeclaredAnnotation(Command.class);
        if(command.isAnnotationPresent(Command.class)){
            Command cmd = anno.getAnnotation(Command.class);
            console.log(command.getName() + " " + cmd.param() + " : " + cmd.description());
        }
    }
}





Aucun commentaire:

Enregistrer un commentaire