检查Generic对象的对象类型的正确方法是什么?

use*_*188 5 java warnings casting object instanceof

编译代码时,我收到了关于Object Casting的警告消息.我不知道如何使用我目前的知识修复它....假设我有一个通用对象MyGenericObj<T>它是从非通用对象扩展的MyObj

这是一个示例代码:

MyObj obj1 = new MyGenericObj<Integer>();
if (obj1 instanceof MyGenericObj) {
    //I was trying to check if it's instance of MyGenericObj<Integer>
    //but my IDE saying this is wrong syntax.... 
    MyGenericObj<Integer> obj2 = (MyGenericObj<Integer>) obj1;
    //This line of code will cause a warning message when compiling 
}
Run Code Online (Sandbox Code Playgroud)

能不能让我知道这样做的正确方法是什么?

任何帮助表示赞赏.

das*_*ght 6

由于类型擦除,没有办法做到这一点:MyGenericObj<Integer>实际上是一个MyGenericObj<Object>幕后,无论其类型参数如何.

解决此问题的一种方法是向Class<T>您的通用对象添加属性,如下所示:

class MyGenericObject<T> {
    private final Class<T> theClass;
    public Class<T> getTypeArg() {
        return theClass;
    }
    MyGenericObject(Class<T> theClass, ... the rest of constructor parameters) {
        this.theClass = theClass;
        ... the rest of the constructor ...
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用getTypeArg查找类型参数的实际类,将其与之进行比较Integer.class,并根据该类做出决策.