【发布时间】:2020-09-09 07:05:40
【问题描述】:
我有两个对象 - 输出(有 20 个字段或属性)和一个对象 o,其中一些字段(从 1 到 5 不等)。
我想比较对象 o 的这 5 个字段的值 在输出对象中使用它们的值。
假设输出对象具有 a 到 z 的属性。并且对象 o 具有 a 到 c 的属性,所以我想将 output.a,output.b 和 output.c 的值与 o.a,o.b 和 o.c 进行比较
注意我不知道 o.a,o.b 和 o.c 是否存在,但我正在动态地从字段中检索它们的属性:
下面是代码。我已经用线标出了什么是有效的,什么是无效的。我不知道如何键入它,因为我不知道属性名称。
private void CompareObjects(Output output,Object o) throws IllegalAccessException, NoSuchFieldException {
Class<?> r = o.getClass();
Field[] fields = respclass.getDeclaredFields();
for (Field field : fields) {
String fname = field.getType().getSimpleName();
print((field.getName())output.getClass().getDeclaredField(fname));// NOT Working error line, not able to typecast it with the field.getName()
// print(field.getType())output.getClass().getDeclaredField(fname)); // NOT Working
}
【问题讨论】:
标签: java reflection