jwa0
jwa0

Reputation: 11

Dynamically call class variables from a string with the class's name

I'm using several classes to store data. Each of these classes has static variables with the same name across classes. I want to load these variables by inputting the name of the class with a string and returning the data from that particular class.

I previously did this by loading an instance of the class via reflection, but I want to do this without actually having to create an instance of the class.

public class dataSet {
static int dataPoint=1;
}
public class otherDataSet {
static int dataPoint=2;
} 
public int returnDataPoint (string className) {
//returns className.dataPoint
}

Upvotes: 1

Views: 515

Answers (1)

Benjamin Urquhart
Benjamin Urquhart

Reputation: 1649

If you insist on using reflection, you don't have to create an instance of the class to access its static members. Just use null instead of the object.

public class dataSet {
static int dataPoint=1;
}
public class otherDataSet {
static int dataPoint=2;
} 

// You can try-catch inside of the method or put a throws declaration on it. Your choice.
public int returnDataPoint (string className) throws Exception {
    Class<?> clazz = Class.forName(className); // edit to include package if needed
    Field field = clazz.getField("dataPoint");
    return field.getInt(null); // calling with null
}

Upvotes: 1

Related Questions