[英]Java - get class properties by string
How can I return a property with String name of it inside a class? 如何在类中返回带有String名称的属性?
My pseudo code is: 我的伪代码是:
class Foo {
public static final String test = "test";
public static String bar(String name) {
return foo.getProperty(name);
}
}
UPDATE UPDATE
I have a class with "setting" name , and this class have a method with getSetting() name , this method get a string key and if a property exist with this key, return the property , if no , search in database for this key,it's nod good solution? 我有一个具有“设置”名称的类,并且该类具有一个具有getSetting()名称的方法,该方法获取字符串键,如果该键存在属性,则返回该属性,如果没有,则在数据库中搜索该键,这是一个好的解决方案?
Try Java Reflection - Fields with #getFields(); 尝试Java反射-使用#getFields()的字段 ;
In your scenario, you can try: 在您的方案中,您可以尝试:
public String getSetting(String strKey){
Class tmp = setting.class;
try {
Field field = tmp.getField(strKey);
return value; // depend on your class instance or field type.
} catch (NoSuchFieldException e) {
// get data from database and return
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.