Java gets a collection of common types

There is already an answer to this question: > get generic type of Java util. List12

if(originalField.getGenericType() instanceof ParameterizedType){
    ParameterizedType pt = (ParameterizedType) originalField.getGenericType();
    Class<?> subClass = (Class<?>) pt.getActualTypeArguments()[0];
}

I also have a collection < string > and it turns out that the collection cannot be converted to parameterizedtype

Someone has an idea how to get a string (or any type will be) from a collection?

I've been reading about Java erasure, so I know this, but after taking the general-purpose program out of the list, I think someone may know another "trick"

thank you.

Editor: I'm iterating all areas of the course:

for (Field originalField : someClass.getDeclaredFields())

Then, when I face some list < string > fields, using the above code, I get string as the subclass variable

Solution

Your method is very good. It should apply to list < string > and collection < string & gt For example, see this example code:

public class Demo {

    List<String> list = new ArrayList<>();
    Collection<String> coll = new ArrayList<>();

    public static void main(String args[]){

        Class<Demo> clazz = Demo.class;
        Field[] fields = clazz.getDeclaredFields();

        for (Field field: fields) {

            Type type = field.getGenericType();

            if (type instanceof ParameterizedType) {

                ParameterizedType pType = (ParameterizedType)type;
                Type[] arr = pType.getActualTypeArguments();

                for (Type tp: arr) {
                    Class<?> clzz = (Class<?>)tp;
                    System.out.println(clzz.getName());
                }
            }
        }
    }
}

This will print out:

java.lang.String
java.lang.String
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>