简体   繁体   中英

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:

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

but how can i know if it represents a generic type... say 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. The standard way of fixing this is to pass in a Class<T> from wherever T is reified and use that class object.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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