简体   繁体   中英

java.lang.NoSuchFieldException: when using reflection

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;
}

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?

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.

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?

Two suggestion:

(1) You can drop the downcast at the first line of the method:

B target = targetClass.newInstance();

(2) Add a try catch so that you can see the name of the missing field. This will help you sort out the issue you're having:

 Field field = null;
 try {
    field = instance.getClass().getDeclaredField(targetField.getName());
 }
 catch(NoSuchFieldException e) {
     throw new RuntimeException("Didn't find field named '" + targetField.getName() + "'");
 }
 ...

Another answer.

If I understand your comment correctly it seems that you have inner classes: Class B (Target) is a class that is defined inside class A. Something like this:

 class A {
   int n;

   class B { 
      int n;
   }
}

Although these two classes seem to have the same fields, and therefore - should not inude a field not found error - they are not.

Inner classes (unless they are defined as static) has a hidden field inserted by the compiler. This field is of the type of the outer class and points to the object that created the inner class object. When using reflection this field is exposed. As A does not have such field, an exception is raised.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM