英文:
How to use instance of dynamically in java?
问题
I have a string variable which stores the name of a class (e.g. String, Integer, etc).
String type = "String";
I have an object which I need to check if it is an instance of the class whose name is stored in the string variable. How do I check it?
if (object instanceof type){
// Do something here
}
However, the above logic doesn't work as the variable type is not recognized as a class. So, how do I dynamically check if an object is an instance of 'type'.
英文:
I have a string variable which stores the name of a class (e.g. String,Integer etc)
String type = "String";
I have an object which i need to check if it is an instance of the class whose name is stored in the string variable. How do I check it ?
if (object instanceof type){
// Do something here
}
However, the above logic doesn't work as the variable type is not recognized as a class. So, how do I dynamically check if an object is an instance of 'type'.
答案1
得分: 3
如果您有类的完全限定名称,您可以使用 Class.forName("java.lang.String").isAssignableFrom(type)
。
如果您没有限定名称,您将不得不编写一个映射,类似于以下方式:
switch (typeName) {
case "String": return type instanceof String;
case "Integer": return type instanceof Integer;
// 等等
}
英文:
If you have the fully qualified name of the class, you can use Class.forName("java.lang.String").isAssignableFrom(type)
.
If you don't have qualified names, you'll have to code out a mapping, something like this:
switch (typeName) {
case "String": return type instanceof String;
case "Integer": return type instanceof Integer;
// et cetera
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论