简体   繁体   中英

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())) {
    //...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM