Search code examples
javaapache-commons-beanutilsindexed-properties

How to get property of arraylist using PropertyUtils


I am using Apache's PropertUtils to get values of bean by passing string parameter. In this particular case I have List of Object and I want to read specific property of an object inside the list, same code to explain

 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);
    } 

I want to read entityId of all the object inside the list. Any help?


Solution

  • java8 streams

    List<String> entityIds = auditModelDTOs.streams().map(p-> (String) PropertyUtils.getProperty(p, "entityId")).collect(Collectors.toList());