4
abstract class A { static int i = 5; } class B extends A { static int i = 6; } class C extends A { static int i = 7; } 

Now I have an ArrayList<Class<? extends A>>. How can I get the value of the static field from an Class<? extends A>?

5
  • 1
    Have you looked at the class Javadoc for Class? Use getDeclaredField. Commented May 26, 2014 at 19:15
  • 1
    Why would you want to do such a painful thing? Are you into self torture? Do you not know that statics are evil -- they make testing really difficult, and code that takes SO to explain is excruciatingly difficult to maintain. Commented May 26, 2014 at 19:17
  • try to make non-static getter which returns you a static variable Commented May 26, 2014 at 19:20
  • @EngineerDollery Well this is for a game, A is the superclass Enemy and B and C are specific types of enemies. I don't see any other way to make a static method in Enemy that takes a difficulty level and returns a new instance of the respective enemy type. Commented May 26, 2014 at 19:26
  • You could, instead, use a factory method and the singleton pattern. The real problem with this approach is that you will find it extremely difficult to write unit tests around code that collaborates with these classes as it will prove torturous to generate a mock instance of them. Commented May 27, 2014 at 14:07

1 Answer 1

7

Try with reflection

Steps to follow:

  • First retrieve the declared field of the class using its variable name
  • Check the type of the returned field
  • Then call corresponding method on Field to get the field value

Sample code:

ArrayList<Class<? extends A>> list = new ArrayList<Class<? extends A>>(); list.add(B.class); list.add(A.class); // get the value of first class stored in array Field f = list.get(0).getDeclaredField("i"); Class<?> t = f.getType(); if (t == int.class) { System.out.println(f.getInt(null)); } 

EDIT

As per @Sotirios Delimanolis comments you can get the value directly without checking field type and mathodField#getX() as shown below but it will return Object instead of primitive int.

Field f = list.get(0).getDeclaredField("i"); System.out.println(f.get(null)); 
Sign up to request clarification or add additional context in comments.

5 Comments

@Sotirios Delimanolis Thanks for getDeclaredField() I tried with getField() first but that access only public member of the class.
What does Class<?> t = f.getType(); if (t == int.class) do? Is it required?
To check for the the type of the field and based on type f.getInt() or f.getDouble() methods are called.
Don't I know that i is an int? So can I just get rid of that?
You can just use Field#get(..), you don't have to go through getX where X is a primitive type.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.