views:

309

answers:

3
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?

+2  A: 

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?

Bozho
Yes, very likely.
Adeel Ansari
+1  A: 

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() + "'");
 }
 ...
Itay
both method give me java.lang.IllegalArgumentException. By the way thanks for the suggestion.
A: 

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.

Itay
Ya I have a inner class in ClassA which is ClassC but in ClassB also have ClassC ClassA and ClassB have exactly the same attriutes.