如何在Java中动态使用实例?

huangapple go评论66阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2023年6月22日 14:10:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76529009.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定