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?
Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.
We can use newInstance() method on the constructor object to instantiate a new instance of the class. Since we use reflection when we don't have the classes information at compile time, we can assign it to Object and then further use reflection to access it's fields and invoke it's methods.
The reflected method may be a class method or an instance method (including an abstract method). A Method permits widening conversions to occur when matching the actual parameters to invoke with the underlying method's formal parameters, but it throws an IllegalArgumentException if a narrowing conversion would occur.
Reflection is an API that is used to examine or modify the behavior of methods, classes, and interfaces at runtime. The required classes for reflection are provided under java.lang.reflect package which is essential in order to understand reflection.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With