1

Is it possible to access a public variable in a class while if the only available access to that class is its .class.
As an example if I have A_VARIABLE in both ClassA and ClassB, if I put the reference to each class Object into an HashSet, am I able to retrieve the A_VARIABLE for each item in the HashSet.

public class ClassA{
    public static final String A_VARIABLE = "ABC";
}

public class ClassB{
    public static final String A_VARIABLE = "123";
}


public class ClassC{
    private void someMethod(){
        HashSet<Class> someClassHashSet = new HashSet<>();
        someClassHashSet.add(ClassA.class);
        someClassHashSet.add(ClassB.class);

        for (Class someClass : someClassHashSet){
            System.out.println("The value is: " + /*someClass.A_VARIABLE*/);
        }
    }
}

Which I would like to print:

The Value is: ABC
The Value is: 123
3
  • ClassA.A_VARIABLE (it's a constant field) and an equals on the class should do the trick Commented Oct 19, 2015 at 5:48
  • @RC wouldn't this mean that he needs to cast his Class objects...? Commented Oct 19, 2015 at 5:53
  • @schneida nope, see Rahul answer Commented Oct 19, 2015 at 7:28

2 Answers 2

3

Yes, you can do that, you'll need reflection which is slower than direct access but still used widely:

for (Class someClass : someClassHashSet){
        Object value = null;
        try {
            value = someClass.getField("A_VARIABLE").get(null);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        System.out.println("The value is: " + value);
}

You see that this code gets the value of a field, that you only reference by a string. The null in .get(null) is because your fields are static. If they were not, you would have to provide an instance of which you'd like to get the value.

Note: Your someMethod() is missing a return value, eg void.

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

Comments

1

You can do it following way

 for (Class someClass : someClassHashSet){
         if (ClassA.class.equals(someClass)) {
            System.out.println("The value is: " + ClassA.A_VARIABLE );  
          } else if (ClassB.class.equals(someClass)) {
            System.out.println("The value is: " + ClassB.A_VARIABLE );
          }
 }

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.