Reference to Classes in Java

Is there any way to make a reference variable to the name of a class?

For example, let's say we have these two classes

class ClassA {
    public static String s = "This is class A";
}

class ClassB {
    public static String s = "This is class B";
}

and then we want to use them like this

// first somehow give the name of ClassA to some variable MyRef

// then print "This is class A"
System.out.print(MyRef.s); 

// then give the name of ClassB to the same variable MyRef

// and then print "This is class B"
System.out.print(MyRef.s);

Is there any way to do this? If not, is there any other simple way to do the same thing, that is, to easily switch between the static variables of ClassA and the static variables of ClassB?

Jon Skeet
people
quotationmark

The closest you could come would be to pass ClassA.class or ClassB.class as a Class and then use reflection to get the field for that class, and its value.

// TODO: Much better exception handling :) (It's almost never appropriate to
// throw Exception...)
public static String getS(Class<?> clazz) throws Exception {
    Field field = clazz.getField("s");
    return (String) field.get(null);
}

Call it with:

String a = getS(ClassA.class);
String b = getS(ClassB.class);

Generally speaking, a better solution would be to use inheritance, but that requires an instance of some superclass or interface, and then a method instead of a field. Of course, that may not fit in with the rest of your requirements - we don't have much idea about the bigger picture of what you're trying to do.

people

See more on this question at Stackoverflow