简体   繁体   中英

How to get generic field type (string representation) with help reflection - Java?

There are some fields:

public class Class1 {
    private Map<String,Integer> field1 = new HashMap<String,Integer>();
    private int someField = 1;
    private int[] myIntArray = new int[]{1,2,3};
    private List<ArrayList<String>> words = null;
    private ArrayList<String>[] group = (ArrayList<String>[])new ArrayList[4];
    private List<List<List<ArrayList<List<List<String>>>>>> lists = null;
}

Is there a simple way to get string representation of each of these (and generally any) types?

Try this:

for (Field field : Class1.class.getDeclaredFields())
    System.out.println(field.getGenericType());

Output:

java.util.Map<java.lang.String, java.lang.Integer>
int
class [I
java.util.List<java.util.ArrayList<java.lang.String>>
java.util.ArrayList<java.lang.String>[]
java.util.List<java.util.List<java.util.List<java.util.ArrayList<java.util.List<java.util.List<java.lang.String>>>>>>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM