我有一个对象初始化如下:
Object obj = new Object(){
final String type = "java.lang.Integer";
final Object value = 6;
};
我想重新创建这个对象:
Integer i = 6;
有什么方法可以获取 obj
对象的 type
字段并使用反射创建一个新实例并将值提供给它?
编辑:在扩展这个问题后,我发现如果我将对象存储在文件中并使用 Jackson 从文件中检索它:
Reader reader = new Reader();
MyClass[] instances = reader.readValue(fileName);
MyClass
定义为:
class MyClass{
List<Object> fields;
.
.
.
}
现在我正在迭代字段
并使用代码将它们转换为适当的对象:
public static Class<?> getTypeForObject(Object field) {
Field returnType = null;
try {
returnType = field.getClass().getDeclaredField("type");
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
return returnType.getType();
}
public static Object getValueForObject(Object field) {
Object obj = null;
try {
obj = field.getClass().getDeclaredField("value").get(field);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
return obj;
}
但是当我观察表达式 field.getClass()
时,它给我 LinkedHashMap
作为它的类。我很困惑为什么以及如果它在内部被视为 Map
如果我想在不使用具体数据结构的情况下通过反射来实现它,那么我还有什么选择可以通用化。
最佳答案
是的,你可以。但是由于 obj
的类型是一个扩展 java.lang.Object
的匿名类,你不能引用它的字段(type
和 value
) 直接,仅通过反射。
这里是你如何做的代码:
String type = (String) obj.getClass().getDeclaredField("type").get(obj);
Object value = obj.getClass().getDeclaredField("value").get(obj);
// Type can be anything, so in order to instantiate it,
// we have to assume something. We assume it has a constructor
// which takes only a String value.
Object recreated = Class.forName(type).getConstructor(String.class)
.newInstance(value == null ? null : value.toString());
System.out.println(recreated);
关于java - 使用反射检索对象的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24670772/