[英]Setting a primitive data type through the use of a Field object
Is there any way to set the value of a primitive through the use of fields? 有什么方法可以通过使用字段来设置基本类型的值? I've tried to play around with the following, but can't seem to get it to work.
我试图尝试以下方法,但似乎无法使其正常工作。
temp[i].setInt(new Object(), new Integer(data[0]));
In this case temp would be an array of declared fields. 在这种情况下,temp将是已声明字段的数组。 The current index i holds a field that holds a primitive int value.
当前索引i包含一个包含原始int值的字段。 Is this sort of thing even possible?
这样的事情有可能吗?
Assuming you have a Map
of field names and values called fieldValues
, and you want to set the values on an instance called myObject
, this code would check the respective primitive type, then set its value appropriately. 假设您具有一个名为
fieldValues
的字段名和值的Map
,并且想要在名为myObject
的实例上设置值,那么此代码将检查相应的原始类型,然后适当地设置其值。
for (String fieldName : fieldValues.keySet())
{
Field field = myObject.getClass().getField(fieldName);
if (field.getType().equals(Integer.TYPE))
{
field.setInt(myObject, Integer.parseInt(fieldValues.get(field.getName());
}
else if (field.getType().equals(Long.TYPE))
{
field.setLong(myObject, Long.parseLong(fieldValues.get(field.getName());
}
else if (field.getType().equals(Boolean.TYPE))
{
field.setBoolean(myObject, Boolean.parseBoolean(fieldValues.get(field.getName());
}
// more else branches for each needed primitive type
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.