Reputation: 4044
For example, I need to get static property from one of my own classes Class1 or Class2 (property name is same for both classes) depend user action. I have only class name in String variable. How to get this property?
Certainly I can to do this:
InfoClass ic;
if(className.equals("Class1")) {
ic=Class1.prop;
} else if(className.equals("Class2")) {
ic=Class2.prop;
}
But that is not so fine solution, I think... Is there another way to implement this?
Upvotes: 1
Views: 4116
Reputation: 11535
You can do this, but as mentioned in the comments it's even less neat than your current solution.
Class clazz = Class.forName(qualifiedClassName);
Field field = clazz.getDeclaredField("prop");
ic = (InfoClass)field.get(null);
It's quite likely that there's a different way to do whatever it is you're doing in your app, which doesn't require reflection or a long list of conditionals; but I don't know enough about your problem to know what that is.
Upvotes: 3
Reputation: 117655
Use reflection:
Class.forName("mypackage.MyClass").getDeclaredField("field").get(null);
Upvotes: 2