mercredi 24 novembre 2021

Java, how to check if one ParameterizedType represents a sub-type of another ParameterizedType?

Given below code snippet, for each field of Pojo class, is there a way to check if the type is an integer list or not? The real problem here is the type argument, since it's quite easy to check if it's a list via instanceof or isAssignableFrom.

Lines in main is what I have found so far, but it does not work for those types with more complex class hierarchy.

Please shed some light here, many thanks.

public class Test {

    public static void main(String[] args) throws NoSuchFieldException {
        // to check if field f1 is an integer list
        Field field = Pojo.class.getField("f1");
        if (List.class.isAssignableFrom(field.getType())) {
            Type type = field.getGenericType();
            if (type instanceof ParameterizedType) {
                ParameterizedType pt = (ParameterizedType) type;
                if (pt.getActualTypeArguments()[0].equals(Integer.class)) {
                    System.out.println("Yes, it's an integer list");
                }
            }
        }

    }

    public static class Pojo {
        public List<Integer> f1;
        public ArrayList<Integer> f2;
        public C1 f3;
        public C2<Integer> f4;
        public C3<Integer> f5; // notice, this is not an integer list, it's a string list
        public C4<Integer> f6;
        public C5<String, Integer> f7;
    }

    public static class C1 implements List<Integer> {...}

    public static class C2<T> implements List<T> {...}

    public static class C3<T> implements List<String> {...}

    public static class C4<T> implements List<Integer> {...}

    public static class C5<T1, T2> implements List<T2> {...}
}




Aucun commentaire:

Enregistrer un commentaire