5

Possible Duplicates:
Java Reflection: Getting fields and methods in declaration order
Java. Get declared methods in order they apear in source code

Suppose I have this class

Is possible take the getters methods in order?

public class ClassA {

private String name;
private Integer number;
private Boolean bool;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Integer getNumber() {
    return number;
}

public void setNumber(Integer number) {
    this.number = number;
}

public Boolean getBool() {
    return bool;
}

public void setBool(Boolean bool) {
    this.bool = bool;
}

}

I have try this..

for (Method method : ClassA.class.getDeclaredMethods()) {
    if (!(method.getReturnType().toString().equals("void"))) {
        method.invoke(obj, new Object[0])));
    }
}

I got this from documentation

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

So.. is just that? Exists some alternative or I just have to implement something?

Community
  • 1
  • 1
coffee
  • 3,048
  • 4
  • 32
  • 46
  • 7
    What is your ultimate purpose in getting the methods in order? – jzd Aug 09 '11 at 13:29
  • I *usually* see these methods returning methods in the source code order, but as you noted that's **not** guaranteed by the spec. And if the JVM doesn't give it to you in that order, there's nothing really you could do about it, except maybe parse the `.class` file manually. – Joachim Sauer Aug 09 '11 at 13:30
  • http://stackoverflow.com/questions/3148274/java-get-declared-methods-in-order-they-apear-in-source-code – tim_yates Aug 09 '11 at 13:35
  • 1
    You can't using reflection, however if you read the byte code you can use the line numbers in the code to determine the original order of method. – Peter Lawrey Aug 09 '11 at 14:57
  • @Peter Interesting. A simple comparison between line numbers looks fine. How can you get the byte code? – coffee Aug 18 '11 at 14:22
  • Use a library like ObjectWeb's ASM. – Peter Lawrey Aug 18 '11 at 16:38

1 Answers1

7

You can add to each method your own @annotation, which contains a number. Then get all the getter methods, and use your custom sorter to sort them depending on the number you passed to the annotation using Collections.sort().

Eg:

@SortedMethod(100)
public String getName()
{
    return name;
}

@SortedMethod(200)
public String getNumber()
{
    return number;
}
Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287