使用 Guava 检查泛型类

kko*_*rad 2 java generics reflection guava

我知道我在这里展示的内容很糟糕,但仍然 - 我需要这样做......我想检查给定方法中的泛型类。我尝试从这里使用番石榴和描述:https : //code.google.com/p/guava-libraries/wiki/ReflectionExplained#Introduction 这是我所拥有的,但我不完全理解为什么它不起作用: ``

abstract static public class IKnowMyType<T> {
    public TypeToken<T> type = new TypeToken<T>(getClass()) {};
}

protected <P> void abc(P el){
    System.out.println(new IKnowMyType<P>(){}.type);
}

protected <P> void abc(){
    System.out.println(new IKnowMyType<P>(){}.type);
}

void test(){
    System.out.println(new IKnowMyType<String>(){}.type); // -> java.lang.String
    this.abc("AA"); // -> P
    this.<String>abc(); // -> P
}
Run Code Online (Sandbox Code Playgroud)

我想得到的是正确的类P(在这种情况下是字符串)而不是P. 这该怎么做?为什么这些abc方法不像我期望的那样工作?

Lou*_*man 6

没有办法做你想做的事情,这完全按预期工作。

类型擦除会在运行时破坏对象的通用类型信息,以及方法的类型参数的知识(就像您在此处找到的那样)。什么类型擦除不影响的是类知道它们的编译时泛型类型,所以例如如果你有

class Foo<T> {}

class Bar extends Foo<String>
Run Code Online (Sandbox Code Playgroud)

然后Bar.class知道它是 的子类Foo<String>,而不仅仅是Foo. 这就是TypeToken工作原理,但它仅在编译时固定类型时才有效;它不能作为类型变量留下。