开发者

Java class object from type variable

Is there a 开发者_如何转开发way to get Class object from the type variable in Java generic class? Something like that:

public class Bar extends Foo<T> {
    public Class getParameterClass() {
        return T.class; // doesn't compile
    }
}

This type information is available at compile time and therefore should not be affected by type erasure, so, theoretically, there should be a way to accomplish this. Does it exist?


This works:

public static class Bar extends Foo<String> {
  public Class<?> getParameterClass() {
    return (Class<?>) (((ParameterizedType)Bar.class.getGenericSuperclass()).getActualTypeArguments()[0]);
  }
}


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜