[英]Get fields and their values at runtime using Java Reflection
I am trying to get fields and their values of an object at runtime. 我试图在运行时获取对象的字段及其值。 Below is the code sample: 下面是代码示例:
public static int calculateProfileStrenght(Object inputObj,
Map<String, Integer> configMap) throws IllegalArgumentException,
IllegalAccessException {
int someValue= 0;
for (Entry<String, Integer> entry : configMap.entrySet()) {
System.out.println("Key=" + entry.getKey() + ", Value="+ entry.getValue());
try {
Field field = inputObj.getClass().getDeclaredField(entry.getKey());
} catch (NoSuchFieldException e) {
System.out.println("No such field: "+entry.getKey());
}
}
return someValue;
}
As shown above, the Map contains key-value pairs, where the key is going to be the field name (or variable name) from inputObj
. 如上所示,Map包含键值对,其中键将是inputObj
的字段名(或变量名)。 I need to read the value of this field from inputObj
. 我需要从inputObj
读取此字段的值。 The datatype of the fields are String, int, Date, etc. inputObj
字段的数据类型为String,int,Date等inputObj
public class UserDetails {
private int userId;
private String userName;
private Date joinedDate;
private Address homeAddress;
private String description;
// getters and setters
}
I can't do field.getLong or getChar, etc since the method is generic and doesn't know about the datatypes of the fields of inputObj
. 我不能执行field.getLong或getChar等,因为该方法是通用的,并且不知道inputObj
字段的数据类型。
I need to read the field values in the for loop and apply the business logic. 我需要读取for循环中的字段值并应用业务逻辑。 Is this even possible? 这有可能吗? I tried a lot of ways but to no luck. 我尝试了很多方法,但是没有运气。 Any references/pointers are appreciated. 任何参考/指针表示赞赏。
如何在Filed中使用此方法:Object get(Object obj)此方法返回指定对象上此Field表示的字段的值。
I missed field.get(Object)
method. 我错过了field.get(Object)
方法。 This will resolve the issue. 这样可以解决问题。
field.getType()
returns the type of the field ( int.class
, Date.class
, etc). field.getType()
返回字段的类型( int.class
, Date.class
等)。 You can easily perform different actions depending on its return value. 您可以根据其返回值轻松执行不同的操作。
Class<?> type = field.getType();
if(type == int.class) {
// load an int
} else if(type == Date.class) {
// load a Date
} else if(type == String.class) {
// load a String
}
// etc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.