Reputation: 3563
Say i have this class
public static final class MyClass {
public static final int A = 4 ;
public static final int[] B = { 1, 2, 3, 4 };
}
I have to access above class and its field values through reflections
Class<?> myClass = getDesiredClass("MyClass");
I am able to get the value of A by this
int a = myClass.getField("A").getInt(myClass);
But how to get value of B, what methods of Field should i use?
int[] b = myClass.getField("B").?
Upvotes: 1
Views: 568
Reputation: 533870
All these are equivalent. I would pick the simplest. ;)
int[] b = MyClass.B;
int[] b = (int[]) MyClass.class.getField("B").get(null);
int[] b = (int[]) Class.forName("MyClass").getField("B").get(null);
Upvotes: 2
Reputation: 198471
An int[]
is an Object
, so just use (int[]) get(myClass)
-- or alternatively, (int[]) get(null)
, since no argument is needed for static fields.
Upvotes: 4