开发者

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 th开发者_StackOverflow中文版e 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜