How to check if this object is an instance of the class name specified in the string?

I have the following variables

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

where is MyObjas follows

package myPackage;

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

How to check if an MyObjinstance of the full class name represented by a string myString?

+3
source share
2 answers

You can use Class#isInstance()for this.

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

Not sure if I understand you correctly, but this may 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
source

All Articles