来自类型变量的 Java 类对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2801267/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 12:59:32  来源:igfitidea点击:

Java class object from type variable

javagenericstype-erasure

提问by Alexander Temerev

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

有没有办法从 Java 泛型类中的类型变量中获取 Class 对象?类似的东西:

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?

此类型信息在编译时可用,因此不应受到类型擦除的影响,因此,从理论上讲,应该有一种方法可以实现这一点。它存在吗?

采纳答案by sfussenegger

This works:

这有效:

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

回答by tkr

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

代码片段有点混乱。T 是类型参数还是类?

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.

实际上,第二个 println 会导致异常。

回答by Brad Parks

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

从这里获取:https: //stackoverflow.com/a/4699117/26510