See if the object is an instance of a class that has passed through a string

I suppose there must be some way to use reflection to do what I want to do.

I need to be able to take a line at runtime related to a specific class, for example:

string s = "mypackage.MySuperClass" 

Then I may have an object of some type. It can be one of the following:

 mypackage.MySuperClass obj = new mypackage.MySuperClass(); 

or

 mypackage.MySubClass obj2 = new mypackage.MySubClass(); 

or

 someotherpackage.SomeOtherClass obj3 = new someotherpackage.SomeOtherClass(); 

What I need to do is see if the object (which is determined by its type at runtime) is equal to the string s (which is also determined at runtime using completely different means).

In the above cases, I would like obj and obj2 to be of the same type as s (since MySubClass is a subclass of MySuperClass), and obj3 will not.

Is there an easy way to do this in java? Maybe something uses instanceOf?

+4
source share
2 answers

It looks like you want something like this:

 boolean isInstance(Object o, String className) { try { Class clazz = Class.forName(className); return clazz.isInstance(o); } catch (ClassNotFoundException ex) { return false; } } 

Or you can do it the other way around - take o class ( o.getClass() ), find all the ancestor classes and compare their names with className .

+7
source

You can use Class.forName(String className) to get a Class based on the passed string value.

If all that bothers you is whether it is an instance of a particular class, you can call isInstance(Object o) on the Class to check if this parameter is an instance of the class.

If you really need a class object, you can call newInstance() on the Class . Then you can check the resulting object with instanceOf for another object.

+1
source

Source: https://habr.com/ru/post/1299858/


All Articles