Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I imagine that there has to be some way to use reflection to do what I want to do.

I need to be able to take a string at runtime that is of a certain class, for example:

string s = "mypackage.MySuperClass"

Then I may have an object of some type. It could 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 an object (which its type is determined at runtime), is equal to the string s (which is also determined at runtime via completely different means).

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

Is there an easy way to do this in java? Possibly something using instanceOf?

like image 411
Brian Avatar asked Feb 28 '23 16:02

Brian


2 Answers

Sounds 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 could do it the other way round - take o's class (o.getClass()), find all ancestor classes and compare their names to className.

like image 179
finnw Avatar answered Mar 05 '23 18:03

finnw


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

If all you're concerned with is whether it is an instance of a particular class, you can then call isInstance(Object o) on the Class to test whether a the parameter is an instance of the class.

If you actually need an object of the class, you can call newInstance() on the Class. You can then test the resulting object with instanceOf against another object.

like image 38
Nate Avatar answered Mar 05 '23 17:03

Nate