开发者

How to check if a given object is an instance of the class name given in a String?

I have the following variables

MyObj myObj = new MyObj();
String myString = "myPackage.MyObj";

where MyObj look like this

开发者_如何学Go
package myPackage;

class MyObj {
    private String one;
    private String two;
}

How can I check if myObj is an instance of the full qualified class name as represented by the string myString?


You can use Class#isInstance() for this.

if (Class.forName(myString).isInstance(myObj)) {
   // myObj is an instance of the class as specified by myString.
}


Not sure I understand you correctly, but this might help you:

Number n = 42;      //Integer, try 42L (Long)
String type = "java.lang.Integer";
//if(n instanceof type)  //?!?
if(Class.forName(type).isAssignableFrom(n.getClass())) {
    //...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜