我想通过以下方式迭代类字段
我有课
public class Parent{
String name;
String lastName;
}
public class Child extends Parent{
int childNumber;
}
在父类中我想要一个“get”方法
孩子将继承
此方法将按名称返回字段的值
我如何检索该字段的值?
我希望方法是这样的:
public Object get(String key){
Field field;
Object result = null;
try {
field = this.getClass().getDeclaredField(key);
if(field!=null) {
field.setAccessible(true);
}
result = field.get(this); // this is where my problem, i don't know how to retrieve the field's value
} catch (NoSuchFieldException | SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
堆栈跟踪
java.lang.IllegalArgumentException: Can not set int field com.database.User.userID to java.lang.String
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(Unknown Source)
at sun.reflect.UnsafeIntegerFieldAccessorImpl.getInt(Unknown Source)
at sun.reflect.UnsafeIntegerFieldAccessorImpl.get(Unknown Source)
at java.lang.reflect.Field.get(Unknown Source)
at com.database.DatabaseObject.get(DatabaseObject.java:106)
at com.database.DatabaseObject.set(DatabaseObject.java:128)
at com.database.DatabaseObject.getInsertPreparedStatement(DatabaseObject.java:64)
at com.database.Database.insert(Database.java:95)
at com.lenabru.webservice.ElectronicArenaWebService.register(ElectronicArenaWebService.java:21)
at com.database.Main.main(Main.java:29)