[英]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 MyObj
看起来像这样
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
?如何检查myObj
是否是由字符串myString
表示的完全限定 class 名称的实例?
You can use Class#isInstance()
for this.您可以为此使用Class#isInstance()
。
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())) {
//...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.