2009-12-23 44 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