Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Reflection: Getting fields and methods in declaration order

Is there any way to get a classes declared fields (and methods) in the order of declaration using reflection? According to the documentation, the ordering of Methods and Fields returned by getFields(), getDeclaredFields(), etc. is undefined.

Specifying something like an index would be possible using annotation as suggested in Java reflection: Is the order of class fields and methods standardized?

Are there any better options, i.e. not having to specify the index manually?

Now before you ask what I need this for: we have a method that takes a quite big data structure as input and performs a lengthy calculation on it. To create unit tests, we made a method that takes an input object and an output instance and creates the Java source code (setting up input, invoking the calculation method, and asserting the correct results afterwards) as output. This code is much more readable when fields are written in declaration order.

like image 346
Axel Avatar asked Feb 15 '11 08:02

Axel


People also ask

How do you inherit fields using reflection?

The only way we have to get only inherited fields is to use the getDeclaredFields() method, as we just did, and filter its results using the Field::getModifiers method. This one returns an int representing the modifiers of the current field. Each possible modifier is assigned a power of two between 2^0 and 2^7.

Which method is used to get methods using reflection?

The getConstructors() method is used to get the public constructors of the class to which an object belongs. The getMethods() method is used to get the public methods of the class to which an object belongs. We can invoke a method through reflection if we know its name and parameter types.

Is it possible to get information about private fields methods using reflection?

Yes it is possible. You need to use the getDeclaredField method (instead of the getField method), with the name of your private field: Field privateField = Test.

How do I stop reflection in Java?

Yes, reflection is slow, and it creates fragile code when used in this way. If you want to avoid the if statement, you should use polymorphism.


1 Answers

With jdk 6, the reflected fields are in deed in their declaration order. In early jdk that wasn't the case. Apparently enough people have nagged.

Although not guaranteed by javadoc, I would still take this order as granted, and I assume the order will be kept in future jdks too.

In your app, like in most apps, the dependency on the declaration order is mostly vanity - your app won't fail if the order screws up, it just become a little uglier.

like image 200
irreputable Avatar answered Sep 29 '22 11:09

irreputable