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 the forum. When I try to reflect an object of the same type, it works, but when I try to create a complex type that means inside ClassA , I got a ClassB object, I got java.lang.NoSuchFieldException . Can anybody help me?

+4
source share
3 answers

You have two different classes, most likely with different sets of fields. Therefore, if your class A does not have the same fields as your class B , then an exception is thrown.

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

What is your ultimate goal with this piece of code?

+3
source

Two suggestions:

(1) You can omit the first line of the method:

 B target = targetClass.newInstance(); 

(2) Add a catch attempt so that you can see the name of the missing field. This will help you solve the question that you have:

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

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 go into the field where the error was not found - this is not so.

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

0
source

All Articles