Get type of a generic parameter in Java with reflection

后端 未结 18 1959
死守一世寂寞
死守一世寂寞 2020-11-22 05:56

Is it possible to get the type of a generic parameter?

An example:

public final class Voodoo {
    public static void chill(List aListWithTy         


        
18条回答
  •  [愿得一人]
    2020-11-22 06:08

    Here is another trick. Use a generic vararg array

    import java.util.ArrayList;
    
    class TypedArrayList extends ArrayList
    {
        @SafeVarargs
        public TypedArrayList (E... typeInfo)
        {
            // Get generic type at runtime ...
            System.out.println (typeInfo.getClass().getComponentType().getTypeName());
        }
    }
    
    public class GenericTest
    {
        public static void main (String[] args)
        {
            // No need to supply the dummy argument
            ArrayList ar1 = new TypedArrayList<> ();
            ArrayList ar2 = new TypedArrayList<> ();
            ArrayList ar3 = new TypedArrayList<> ();
        }
    }
    

提交回复
热议问题