Java: instanceof Generic

房东的猫 提交于 2019-11-28 18:14:03

Generics are a compile time feature. Generics add checks at compile time which may not have any meaning at runtime. This is one example. You can only check the type of the object referenced which could be a super type in code. If you want to pass the type T you have do this explicitly.

void someMethod(Class<T> tClass) {
    if(String.class.isAssignableFrom(tClass)) 

or

void someMethod(Class<T> tClass, T tArg) {

Note: the type might not be the same,

someMethod(Number.class, 1);
Tomasz Krzyżak

if you have subclass

public class SomeClass extends SomeSubclass<String>{}

and

public class SomeSubclass<T> {}

then there is a way to discover type of T by executing code

Type t = getClass().getGenericSuperclass()
if (t instanceof ParameterizedType) {
    Type[] actualTypeArguments = ((ParameterizedType)t).getActualTypeArguments()
    // in simple cases actualTypeArguments will contain Classes, since Class implements Type
}

if your case are a bit more complex (? extends String)` take a look at org.ormunit.entity.AEntityAccessor#extractClass

It won't compile because T is not a variable, but a place holder for a class that is defined at runtime. Here's a quick sample:

public class Test<T> {

public void something(T arg) {
    if (arg instanceof String) {
        System.out.println("Woot!");
    }
}

public static void main(String[] args) {
    Test<String> t = new Test<String>();
    t.something("Hello");
}

}

If you have specific field you can just check it like below:

private <T> String someMethod(T genericElement)
{
    if (String.class.isInstance(genericElement))
    {
        return (String) genericElement;
    }
...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!