我正在使用反射來讀取類的屬性及其值。有字符串,布爾類型和類屬性。如何獲取類類型的值。反射 - 讀取類的屬性而不是字符串或int
User.java
private String firstName;
private String lastName;
private SupportLangauge flang;
private SupportLangauge mlang;
SupportLanguage.java
private String languageCode;
private Boolean flang;
private Boolean mlang;
我能救法蘭面的數據,使用反射mlang,但無法讀取值。當我閱讀時,對象正在返回。見下面的示例。
結果:
"flang": "[email protected]
[\r\n languageCode=EN_US\r\n]",
"mlang": "[email protected]
[\r\n languageCode=EN_US\r\n]",
我下面的代碼保存的語言類型。
SavingUser.java
for (User user : CollectionsUtilService.nullGuard(userList)) {
PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(
user.getClass()).getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
if (fieldValueMap.containsKey(propertyDescriptor.getName())) {
if (propertyDescriptor.getPropertyType().getName().
equalsIgnoreCase("com.sample.entity.user.SupportLanguage")) {
String langString = fieldValueMap.
get(propertyDescriptor.getName());
SupportLanguage s = new SupportLanguage();
s.setLanguageCode(langString);
propertyDescriptor.getWriteMethod().invoke(user, s);
}
}
}
}
我對閱讀的價值準則;
RenderingUser.java
if (propertyDescriptor.getPropertyType().
getName().equalsIgnoreCase
("com.sample.entity.
user.SupportLanguage")) {
Method m = propertyDescriptor.getReadMethod();
SupportLanguage s = new SupportLanguage();
System.out.println("m.invoke(SupportLanguage) "
+ m.invoke(s));
你得到的輸出'com.sample.entity.user.SupportLanguage @ 3080037d'因爲類'SupportLanguage'不會覆蓋'的toString()'方法;請參閱[如何在不獲取「SomeType @ 2f92e0f4」的情況下打印我的Java對象?](http://stackoverflow.com/questions/29140402/how-do-i-print-my-java-object-without-getting-sometype2f92e0f4 ) – Jesper