[code fragment] and [Java] extract an E item in the List and return a new sublist

There is a requirement in the recent project. You need to extract one of the projects from a List to generate a new List. Here is the implementation code.

 1 //From one List<T>Draw out T Project specified in( E Type), return a List<E>
 2 //srtList Extraction source List
 3 //tClass source List in Item Type ( T Custom class)
 4 //eClass source List in Item Type of item to extract from class E(Stringd And so on.
 5 //fieldName Project name to be extracted (note that this will be used in the tool fieldName Generate corresponding get Method,Therefore, there must be a 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     //Get method name getXXX
10     String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
11 
12     try {
13         //Through the given class name, the instance of the class is generated, and then the reference of the specified method name of the instance is obtained.
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             //target of execution t The specific method of (the method name obtained earlier method)
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);

One thing you need to pay attention to when you get the method name is that you need to create an instance of T, tClass.newInstance(), then get the class of this instance, and then get the reference of the specified method.

If you don't instantiate and directly use tClass.getMethod, you won't get the actual method. If you use tClass.getMethods, you will get the corresponding method of the Object class.

Usage:

List < UserInfo > srcList; (this is the source list, which stores UserInfo. UserInfo contains name and other items.)

List<String> targetList = ListUtil.getItemListFromList(srcList, UserInfo.class, String.class,"name");

Tags: Java

Posted on Thu, 02 Apr 2020 20:54:01 -0700 by corbin