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
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())) {
//...
}
精彩评论