Java class object from type variable

前端 未结 3 1294
有刺的猬
有刺的猬 2020-12-23 22:14

Is there a way to get Class object from the type variable in Java generic class? Something like that:

public class Bar extends Foo {
    public Clas         


        
相关标签:
3条回答
  • 2020-12-23 22:28

    This code works for derived classes as well:

    import java.lang.reflect.ParameterizedType;
    
    public abstract class A<B> 
    {
        public Class<B> getClassOfB() throws Exception 
        {
            ParameterizedType superclass = (ParameterizedType) getClass().getGenericSuperclass();
    
            return (Class<B>) superclass.getActualTypeArguments()[0];
        }
    }
    

    snagged from here: https://stackoverflow.com/a/4699117/26510

    0 讨论(0)
  • 2020-12-23 22:30

    The code snippet is a bit confusing. Is T a type parameter or a class?

    public static class Bar extends Foo<String> {
        public Class<?> getParameterClass() {
            return (Class<?>) (((ParameterizedType)Bar.class.getGenericSuperclass()).getActualTypeArguments()[0]);
        }
    }
    
    public static class Bar2<T> extends Foo<T> {
        public Class<?> getParameterClass() {
            return (Class<?>) (((ParameterizedType)Bar2.class.getGenericSuperclass()).getActualTypeArguments()[0]);
        }
    }
    
    
    public static void main(String[] args) {
        System.out.println(new Bar().getParameterClass());
        System.out.println(new Bar2<Object>().getParameterClass());
    }
    

    Actually the second println will cause an exception.

    0 讨论(0)
  • 2020-12-23 22:48

    This works:

    public static class Bar extends Foo<String> {
      public Class<?> getParameterClass() {
        return (Class<?>) (((ParameterizedType)Bar.class.getGenericSuperclass()).getActualTypeArguments()[0]);
      }
    }
    
    0 讨论(0)
提交回复
热议问题