我正在使用Apache的PropertUtils通过传递字符串参数来获取bean的值。 在这种特殊情况下,我有对象列表,我想读取列表中对象的特定属性,相同的代码来解释
List<AuditModelDTO> auditModelDTOs = new ArrayList<>();
AuditModelDTO amd1 = new AuditModelDTO();
amd1.setEntityId("e1");
amd1.setParamResponse(false);
AuditModelDTO amd2 = new AuditModelDTO();
amd2.setEntityId("e2");
amd2.setParamResponse(true);
auditModelDTOs.add(amd1);
auditModelDTOs.add(amd2);
Object requiredObjectProperty = null;
try {
requiredObjectProperty = PropertyUtils.getProperty(auditModelDTOs,"get().entityId");
IndexedProperty(auditModelDTOs,"get(0).entityId",1);
} catch (Exception e) {
log.error("Caller does not have access to the property accessor method. Exception thrown is {}", e);
throw new AuditException(AuditError.ILLEGAL_ACCESS_FOR_PROPERTY_ACCESSOR, e);
}
我想阅读列表中所有对象的entityId
。
有什么帮助吗?
答案 0 :(得分:1)
java8 streams
foreach($model->receiver_id as $r_id){
$save = new YourModel();
$save->yourProperty = $model->yourProperty;
....
$save->receiver_id = $r_id;
$save->save();
}
答案 1 :(得分:0)
您可以使用此方法获取基于对象和属性名称的属性数据
public static String getPropertyValue(Object object, String propertyName) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException
{
String strValue = "";
Class< ? > c = object.getClass();
Field f = c.getDeclaredField(propertyName);
f.setAccessible(true);
Object value = f.get(object);
if (value != null)
{
strValue = value.toString();
}
return strValue;
}
答案 2 :(得分:0)
像这样的完整功能:
public static void main(String[] args)
{
List<AuditModelDTO> auditModelDTOs = new ArrayList<>();
AuditModelDTO amd1 = new AuditModelDTO();
amd1.setEntityId("e1");
amd1.setParamResponse(false);
AuditModelDTO amd2 = new AuditModelDTO();
amd2.setEntityId("e2");
amd2.setParamResponse(true);
auditModelDTOs.add(amd1);
auditModelDTOs.add(amd2);
System.out.println("EntityId list : " + getEntityId(auditModelDTOs));
}
// GetEntityIdList
public static List<String> getEntityIdList(List<Object> auditModelDTOs)
throws SecurityException,
IllegalArgumentException,
NoSuchFieldException,
IllegalAccessException
{
List<String> entityIdList = new ArrayList<String>();
String propertyName = "entityId";
for (Object object : auditModelDTOs)
{
if (object != null)
{
entityIdList.add(getPropertyValue(object, propertyName));
}
}
return entityIdList;
}
// getPropertyValue
public static String getPropertyValue(Object object, String propertyName)
throws NoSuchFieldException,
SecurityException,
IllegalArgumentException,
IllegalAccessException
{
String strValue = "";
Class< ? > c = object.getClass();
Field f = c.getDeclaredField(propertyName);
f.setAccessible(true);
Object value = f.get(object);
if (value != null)
{
strValue = value.toString();
}
return strValue;
}