嗨,我有下面的密码:
ModuleA.Student student 1 = null;
ModuleB.Student student 2 = null;
student2 = retrieveStudentFacade().findStudentbyName("John");
student1 = StudentSessionEJBBean.convert(student2,ModuleA.Student.Class);
现在的问题是学习1.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;
}
发布于 2009-12-22 19:35:53
真的,你不想这么做!好吧,你也许想这么做.但你真的不应该这么做。
与其使用反射,不如使用该语言并提供如下构造函数:
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();
}
}
代码中要修复的内容:
发布于 2009-12-22 19:04:32
你确定你没有吞咽任何例外吗?
我建议您使用setter/getter方法,而不是直接访问字段。您可以提取类似于字段的方法,然后在对象上调用它们。
尽管代码变得复杂,但您应该能够实现您想要的。
像bean复制实用程序这样的工具也使用getter/setter (这就是为什么它们只在“bean”上工作,它有符合命名约定的getter/setter)。
发布于 2009-12-22 22:50:41
您想要做的事情背后的目的可能很奇怪(共享它们),但是有比手动使用反射更好的方法。
但是您需要公共设置器/getter来获取您想要复制的属性(而且无论如何您都应该拥有它们),并且您必须事先创建目标对象的实例。
https://stackoverflow.com/questions/1950429
复制