[Code fragment] [Java] extracts an E project from the List <T> and returns a new sub-List <E>, javalist
There is a need for a recent project. You need to extract one of the projects from a List to generate a new List. The following is the implementation code.
1 // from a List <T>, extract the specified project (E type) from T ), returns a List <E> 2 // srtList extracted from the source List 3 // The type of the Item in the tClass source List (T custom class) 4 // The Type E (Stringd) of the project to be extracted from the Item class in the eClass source List. 5 // the name of the project to be extracted from fieldName (note, the tool uses fieldName to generate the corresponding get method. Therefore, this class must have the corresponding Get method.) 6 public static <T, e> List <E> getItemListFromList (List <T> srtList, Class <T> tClass, Class <E> eClass, String fieldName) {7 List <E> rtnList = new ArrayList <E> (); 8 Method method = null; 9 // Obtain the method name getXXX10 String methodName = "get" + fieldName. substring (0, 1 ). toUpperCase () + fieldName. substring (1); 11 12 try {13 // generate an instance of the class using the given class name, and then obtain the reference of the specified Method Name of the instance. 14 method = (tClass. newInstance ()). getClass (). getMethod (methodName); 15} catch (NoSuchMethodException e) {16 e. printStackTrace (); 17} catch (InstantiationException e) {18 e. printStackTrace (); 19} catch (IllegalAccessException e) {20 e. printStackTrace (); 21} 22 23 for (T t: srtList) {24 E obj = null; 25 try {26 // execute the specific method of object t (method obtained earlier) 27 obj = (E) method. invoke (t); 28 rtnList. add (obj); 29} catch (IllegalAccessException e) {30 e. printStackTrace (); 31} catch (InvocationTargetException e) {32 e. printStackTrace (); 33} 34} 35 return rtnList; 36}
Method = (tClass. newInstance (). getClass (). getMethod (methodName );
Note that when getting the method name, you need to convert it into a T instance, tClass. newInstance (), then obtain the class of this instance, and then obtain the reference of the specified method.
If tClass. getMethod is used directly without instantiation, no actual method is available. If tClass. getMethods is used, the corresponding method of the Object class is obtained.
Usage:
List <UserInfo> srcList; (this is the source List, which stores UserInfo, and UserInfo contains name and other items)
List <String> targetList = ListUtil. getItemListFromList (srcList, UserInfo. class, String. class, "name ");