3

Is there any way this can be done:

Class cls = MyClass.class;
int variable = cls.staticVariable;

Class MyClass {
    public static int staticVariable = 5;
}

Class cls will always contain a class that has the variable staticVariable, but it won't always be the same class. Hope you understand.

5
  • Why don't you try and see for yourself? Commented Aug 20, 2013 at 9:09
  • @AniketThakur Well that doesn't work, I was just for explaining my problem. Commented Aug 20, 2013 at 9:10
  • ok did not get your question. Try Reflection APIs. docs.oracle.com/javase/tutorial/reflect Commented Aug 20, 2013 at 9:13
  • possible duplicate of Accessing static field from Class<A> variable Commented Aug 20, 2013 at 9:13
  • This is really error prone. Stay away from such solutions whenever possible. Commented Aug 20, 2013 at 9:21

2 Answers 2

4

Here is a short working example demonstrating the concept via reflection.

public class ReflectionStatic {

    public static int staticVariable = 5;

    public static void main(String[] args) throws IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException {
        Class<ReflectionStatic> clazz = ReflectionStatic.class;
        int value = clazz.getField("staticVariable").getInt(null);
        System.out.println(value);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Yes, but only via the reflection API.

Field f = cls.getField("staticVariable");
int variable = f.getInt(null);

There will be a lot of exceptions for you to catch here.

Comments

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.