2009-12-23 48 views
1

嗨,我得到了下面的代码:的Java 2个反映对象

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

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

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

UPDATE

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

回答

0

的getFields方法只返回公开访问的字段(即不是私有,保护,或包访问的Javadoc中。

返回数组包含Field反映所有可访问的类或接口的公共领域的对象

我认为你关心的id字段是私人的,所以你应该改用getDeclaredFields方法。

返回Field对象反映此Class对象所表示的类或接口声明的所有字段的数组。这包括公共,受保护,默认(包)访问和专用字段,但不包括继承字段。

要反射性地设置从此方法返回的(私有)字段,您还需要调用field.setAccessible(true)。

+0

嗨我的ModuleB.Student的属性是私人的ModuleA.Student实际上是一个代理被保护 – user236501 2009-12-23 03:04:02

1

你确定你没有吞咽任何异常?

我建议你使用setter/getter方法,而不是直接访问字段。您可以像字段一样提取方法,然后在对象上调用它们。

尽管代码变得复杂,您应该能够实现您想要的。

像bean copy utils这样的工具也使用getter/setter(这就是为什么它们只能在“bean”上工作,它们的getter/setter符合命名约定)。

+0

嗨,我遇到了一个异常,你能帮我吗? – user236501 2009-12-23 03:22:09

+1

有什么例外? – TofuBeer 2009-12-23 03:36:19

+0

班级无法访问修饰符类的成员“私人”反映 – user236501 2009-12-23 03:48:46

2

真的,真的,你真的不想这么做!那么你可能想要这样做......但你真的真的不应该这样做。

而不是使用反射使用的语言,并提供这样的构造:

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()”(或记录它),以便您可以查看是否出现了问题。

+0

对不起,阅读该问题,我不真正了解问题。我很欣赏英语不是你的第一语言,但你将不得不清理你的问题,使其更容易理解。 – TofuBeer 2009-12-23 03:44:28