简体   繁体   English

Java:是否可以比较一个类 <?> 具有通用类型参数的对象?

[英]Java: Is it possible to compare a Class<?> object with a generic type parameter?

Suppose i have a list of classes: 假设我有一个类别列表:

List<Class<?>> classes;

If i now take one of these classes, lets say... the second, and would want to know if it represents the String class, i would do the following: 如果我现在选择这些类之一,那么说...第二个,并且想知道它是否表示String类,我将执行以下操作:

classes.get(1).equals(String.class)

but how can i know if it represents a generic type... say T? 但是我怎么知道它是否代表一个泛型...说T?

class Foo<T> {

    void someMethod(){

        System.out.println(classes.get(1).equals(T)); //error: T cannot be resolved to a variable
    }
}

i tried 我试过了

T.class
(Class<T>)T

But nothing works. 但是什么都行不通。 I would really like to know if this is possible, and if it is, how to achieve it. 我真的很想知道这是否可能,如果可能,如何实现。
Thanks for your attention! 感谢您的关注! =) =)

This is not possible in Java, due to type erasure ( http://en.wikipedia.org/wiki/Type_erasure ) - T does not actually exist at runtime, it only exists as information for the compiler. 由于类型擦除( http://en.wikipedia.org/wiki/Type_erasure ),在Java中这是不可能的T在运行时实际上并不存在,它仅作为编译器的信息存在。 The standard way of fixing this is to pass in a Class<T> from wherever T is reified and use that class object. 解决此问题的标准方法是从T任何地方传入Class<T>并使用该类对象。

这是不可能的,但是您可以为类提供一些包装器,这些包装器将使用一种返回类型的方法来实现简单接口,然后将该接口作为通用类型传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM