1

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
}
1
  • 1
    If you posted your code that works with instances, it would be easy to modify that to work with statics. But why would you do something that is not the right way to do it in Java, and is several orders of magnitude slower than doing it the right way? You shouldn't use reflection at all - just have a class DataSet that has data points in it and create multiple instances of it. Commented Jun 10, 2019 at 2:45

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

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.