Get list of attributes of an object in an List

前端 未结 8 1720
青春惊慌失措
青春惊慌失措 2020-12-12 19:12

When there is an List, is there a possibility of getting List of all person.getName() out of that? Is there an prepared call for that

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-12 19:28

    Not tested but this is the idea:

    public static  List getAttributeList(List list, Class clazz, String  attribute)    
    {
        List attrList= new ArrayList();
    
        attribute = attribute.charAt(0).toUpperCase() + attribute.substring(1); 
        String methodName = "get"+attribute;
    
        for(Object obj: personList){
            T aux = (T)clazz.getDeclaredMethod(methodName, new Class[0]).invoke(obj, new Object[0]);
            attrList.add(aux);
        }
    }
    

提交回复
热议问题