java.lang.NoSuchFieldException:使用反射时 [英] java.lang.NoSuchFieldException: when using reflection

查看:35
本文介绍了java.lang.NoSuchFieldException:使用反射时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public static <A, B> B convert(A instance,
                           Class<B> targetClass) throws Exception {
  B target = (B)targetClass.newInstance();

  for (Field targetField : targetClass.getDeclaredFields()) {
    targetField.setAccessible(true);
    Field field =
        instance.getClass().getDeclaredField(targetField.getName());
    field.setAccessible(true);
    targetField.set(target, field.get(instance));
  }
  return target;
}

以上是我从论坛获得的代码,当我尝试反映单个类型对象时它可以工作,但是当我尝试在 ClassA 中表示复杂类型时,我得到了 ClassB 对象,我得到了 java.lang.NoSuchFieldException.有人可以帮我吗?

Above is the code I get from forum, When I try to reflect an single type object it works, but when I try on the complex type which mean inside ClassA I got ClassB object, I got the java.lang.NoSuchFieldException. Can anyone help me?

推荐答案

您有两个不同的类,它们很可能具有不同的字段集.因此,如果您的 A 类与您的 B 类没有相同的字段,则会引发异常.

You have two different classes, with, most likely, different set of fields. So if your Class A doesn't have the same fields as your class B, then the exception is thrown.

我建议使用 BeanUtils.copyProperties(source, target) 来自 apache commons-beanutils.您只需自己创建第二个对象,并将其传递给该方法.如果字段不同,则不会抛出异常.

I'd suggest using BeanUtils.copyProperties(source, target) from apache commons-beanutils. You just create the second object yourself, and pass it to the method. It will not throw an exception if fields differ.

您使用这段代码的最终目标是什么?

What is your ultimate goal with this piece of code?

这篇关于java.lang.NoSuchFieldException:使用反射时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆