我目前正在使用反射来获取 GUI 类的声明字段。但是,我找不到一种方法可以将字段类型转换为我需要的对象。
我需要的是能够获取 Field 的实际对象,因此,如果返回的字段是 JLabel 类型,我需要能够在 JLabel 中对字段进行类型转换才能访问该对象
以下是我正在使用的代码,但是未检索实际的对象组件:
for (int i = 0; i< fields.length; i++) {
this.fields.add(fields[i]);
Class<?> fieldType = fields[i].getType();
try {
Component c = (Component) fieldType.newInstance();
System.out.println(c.getX + " " + c.getY());
} catch (InstantiationException ex) {
Logger.getLogger(HeatMap.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(HeatMap.class.getName()).log(Level.SEVERE, null, ex);
}
}
最佳答案
我想你想做这样的事情,不是吗?
(SomeSubClass)fieldType.newInstance();
我进一步假设 fieldType
是 SomeSubClass
的父类(super class),因此您会得到一个异常(很可能是 ClassCastException
)。
示例:
class A {}
class B extends A{}
fieldType = A.class;
//this would throw an exception since A it NOT a B!
(B)fieldType.newInstance();
编辑:
要将对象转换为您需要的对象,请使用 instanceof
关键字。
示例:
Object value = field.get(objectTheFieldBelongsTo);
if( value instanceof JLabel) {
JLabel labelValue = (JLabel)value;
//whatever you want
}
关于java - 如何将反射字段类型转换为另一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9906690/