我知道我在这里呈现的内容不好,但是仍然-我需要这样做...
我想检查给定方法中的泛型类。我尝试从这里使用番石榴和描述: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
}


我想得到的是P的正确类(在这种情况下为String),而不是P。这该怎么做?为什么这些abc方法不能按我预期的那样工作?

最佳答案

无法执行您要尝试执行的操作,并且此操作完全按预期进行。

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

class Foo<T> {}

class Bar extends Foo<String>


然后Bar.class知道它是Foo<String>的子类,而不仅仅是Foo。这就是TypeToken的工作方式,但是只有在编译时将类型固定时才起作用。它不能保留为类型变量。

10-04 12:10