Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java reflection get all private fields

I wonder is there a way to get all private fields of some class in java and their type.

For example lets suppose I have a class

class SomeClass {     private String aaa;     private SomeOtherClass bbb;     private double ccc; } 

Now I would like to get all private fields (aaa, bbb, ccc) of class SomeClass (Without knowing name of all fields upfront) and check their type.

like image 685
user2152361 Avatar asked Mar 09 '13 20:03

user2152361


People also ask

Can Java reflection API access private fields?

If we want to access Private Field and method using Reflection we just need to call setAccessible(true) on the field or method object which you want to access. Class. getDeclaredField(String fieldName) or Class. getDeclaredFields() can be used to get private fields.

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

Yes it is possible.

How is private field called using reflection?

Accessing private fields in Java using reflection In order to access a private field using reflection, you need to know the name of the field than by calling getDeclaredFields(String name) you will get a java. lang. reflect. Field instance representing that field.

How do you get all fields in a class?

The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.


1 Answers

It is possible to obtain all fields with the method getDeclaredFields() of Class. Then you have to check the modifier of each fields to find the private ones:

List<Field> privateFields = new ArrayList<>(); Field[] allFields = SomeClass.class.getDeclaredFields(); for (Field field : allFields) {     if (Modifier.isPrivate(field.getModifiers())) {         privateFields.add(field);     } } 

Note that getDeclaredFields() will not return inherited fields.

Eventually, you get the type of the fields with the method Field.getType().

like image 159
Cyrille Ka Avatar answered Oct 02 '22 17:10

Cyrille Ka