Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading