【发布时间】:2012-01-08 19:21:43
【问题描述】:
样品不工作:
Object o = ...; // The object you want to inspect
Class<?> c = o.getClass();
Field f = c.getDeclaredField("myColor");
f.setAccessible(true);
String valueOfMyColor = (String) f.get(o);
此代码中的问题是您必须使用 String 类进行强制转换。我正在寻找的是能够从其名称中找到属性的类。
例如:
class Brush {
Color myColor;
}
//Somewhere else, in a far far away galaxy
Class<?> c = getMyClassFromAttributeName("myColor");
// and c should be of type Color
我试过了
Field f = this.getClass().getDeclaredField(code);
Class<?> c1 = f.getClass(); //Gives Field
Class<?> c2 = f.getDeclaringClass(); //Gives Brush
谢谢!
PS: 使用来自In Java, how to get attribute given the string with its name?的示例代码
【问题讨论】:
标签: java class reflection dynamic attributes