1

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").?

2 Answers 2

4

An int[] is an Object, so just use (int[]) get(myClass) -- or alternatively, (int[]) get(null), since no argument is needed for static fields.

Sign up to request clarification or add additional context in comments.

Comments

2

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);

1 Comment

Thanks for your quick reply too and detail explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.