Alex Rivera | Logout

Is there something like instanceOf(Class<?> c) in Java?

Asked 2009-06-04T08:53:55.823
102

I want to check if an object o is an instance of the class C or of a subclass of C.

For instance, if x is of class Point I want x.instanceOf(Point.class) to be true and also x.instanceOf(Object.class) to be true.

I want it to work also for boxed primitive types. For instance, if x is an Integer then x.instanceOf(Integer.class) should be true.

Is there such a thing? If not, how can I implement such a method?

Edit
Report

2 Answers

10
x instanceof Integer
x instanceof Object

you just have to use the right syntax

for primitve types, you have to do it completely different. Since you cannot create methods for them , you need a class that keeps the method. So instead of "x.instanceOf(Integer.Class)", you have to call "MyClassComparer.instanceOf(x, Integer.Class)" or something like that. This could easily be implemented by overloading methods, but I fail to see a case when that functionality would be desireable at all.

answered 2009-06-04T08:56:44.290
5

In fact in Java there's a boolean operator called instanceof which can be used to determine if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

if(obj instanceof SomeClass) {
    // Do something
}

The Java Tutorial has a good example of this operator

answered 2009-06-04T08:58:01.807

Your Answer