嗨,我得到以下代码:

ModuleA.Student student 1 = null;
ModuleB.Student student 2 = null;

student2 = retrieveStudentFacade().findStudentbyName("John");
student1 = StudentSessionEJBBean.convert(student2,ModuleA.Student.Class);


现在的问题是student1.getId();返回null,但应该返回一个值。下面是转换器方法,有人指导我使用此方法来反映对象。它工作得很好,因为没有错误发生,只是没有值返回?

更新

   public static <A,B> B convert(A instance, Class<B> targetClass) throws Exception {
B target = (B) targetClass.newInstance();
for (Field targetField: targetClass.getDeclaredFields()) {
    Field field = instance.getClass().getDeclaredField(targetField.getName());
    field.setAccessible(true);
    targetField.set(target, field.get(instance));
}
return target;
}

最佳答案

真的,真的,真的,您不想这样做!好吧,您可能想要这样做...但是您确实真的不应该这样做。

与其使用反射,不如使用语言并提供如下构造函数:

package ModuleA;  // should be all lower case by convention...

public class Student
{
    // pick differnt names for them is a good idea... 2 classes called Student is asking for trouble
    public Student(final ModualB.Student other)
    {
        // do the copying here like xxx =  other.getXXX();
    }
}


代码中要解决的问题:


不要声明方法“引发异常”,因为您必须拥有“ catch(Exception ex)”,否则可能导致您在代码中隐藏错误。
(猜测)至少在catch块中执行“ ex.printStackTrace()”(或记录它),以便您可以查看是否出了问题。

10-08 08:42
查看更多