我试图使用for循环遍历Object类的ArrayList实例:

for(PayloadDTO payloadDTO:payloadDTOList) {
    if(payloadDTO.getEntType().equals(CommonConstants.CUSTOMENTTYPEROLEID.RES_ROLE_TYPE)) {
        resRoleNameList.add(payloadDTO.getEntName());
    }
}


java - 无法迭代包含链接哈希图的arraylist-LMLPHP

这给了我以下错误:

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.alnt.fabric.external.model.PayloadDTO
    at com.alnt.fabric.external.rbac.service.ExternalFabricService.loadImpactedUserCount(ExternalFabricService.java:384)
    at com.alnt.fabric.external.rbac.controller.ExternalFabricController.loadImpactedUserCount(ExternalFabricController.java:160)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)


所以我尝试使用下面的代码将其转换:

payloadDTOList = convert(payloadDTOList.toString(), List<PayloadDTO.class>);


    public static <T> T convert(String json, Class<T> type) throws ALNTApplicationException {
    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.readValue(json, type);
    } catch (Exception e) {
        throw new ALNTApplicationException(FabricComponentErrorCodes.ACTION_HANDLER_ERROR_CODE,"Object conversion error");
    }
}

最佳答案

尝试使用for循环进行投放

for (int i=0; i < payloadDTOList.size(); i++) {
    PayloadDTO payloadDTO = (PayloadDTO) payloadDTOList.get(i);
    if(payloadDTO.getEntType().equals(CommonConstants.CUSTOMENTTYPEROLEID.RES_ROLE_TYPE)) {
      resRoleNameList.add(payloadDTO.getEntName());
    }
}

10-06 13:37