rapadura
rapadura

Reputation: 5300

How can I get the Array field of a class with reflection?

My class A has

   AClaz[] rofl;

The documentation for getDeclaredFields says "This method returns an array of length 0 if the class or interface declares no fields, or if this Class object represents a primitive type, an array class, or void. "

I want to access the rofl array of type AClaz using reflection. Even if the AClaz is an inner class of class A.

So I would do getDeclaredClass ?

Upvotes: 1

Views: 12865

Answers (3)

MAK
MAK

Reputation: 615

you can get fields like this...

Class<?> arrayClass = String[].getClass();
Field[] fields =  arrayClass.getDeclaredFields();
for(int i =0; i<fields.length; i++){

  if(fields[i].isArray()){
//array type fields can be checked like this
    fields[i] is array
  }
}

Upvotes: 0

AlexR
AlexR

Reputation: 115328

getDeclaredFields() returns all fields, i.e. instances of class Field. You want to access one of the fields named rofl, so you can either iterate over array returned by getDeclaredFields() or use getDeclaredField("rofl"). Then, once you have instance of Field you can access the field value itself using set() and get(). If you want to set the value you have to provide value of correct type, i.e. array of AClaz.

If you want to change one element of existing array stored in field rofl in your class you should say something like this: Array.set(field.get(instance), index, element)

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500275

You're misreading the documentation - it's talking about calling getDeclaredFields on an array class, like this:

Class<?> arrayClass = String[].getClass();
Field[] fields = arrayClass.getDeclaredFields();

You should be able to get the field from A without any problem using

Field[] fields = A.class.getDeclaredFields();

and then iterate over the array, or

Field roflField = A.class.getDeclaredField("rofl");

The fact that the field type is an array is not a problem at all.

Upvotes: 6

Related Questions