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