if (obj instanceof classVariable) ?

N

natG

Hi;

How can I check if an object is an instance of a class where the class is
represented in a Class variable?

boolean checkInstance(Object obj, Class c){
if (obj instanceof c) does NOT WORK!
}

thanks
-nat
 
H

Harald Hein

natG said:
Hi;

How can I check if an object is an instance of a class where the
class is represented in a Class variable?

If you don't need inheritance

if(obj.getClass().equals(c))
 
S

Skippy

How can I check if an object is an instance of a class where the
If you don't need inheritance

if(obj.getClass().equals(c))

if(obj.getClass().toString().equals(c.toString()))

or maybe (don't know) :

if(object.getClass() == c)
 
R

Rach

How can I check if an object is an instance of a class where the class
is represented in a Class variable?
boolean checkInstance(Object obj, Class c){
if (obj instanceof c) does NOT WORK!
}

You can only use instance of statically, if you want to dynamically check an
object is of a type of a class, then use

obj.getClass().equals(clazz);

or for inheritence,

clazz.isAssignableFrom(obj.getClass());
 
K

Ken Sprague

The java.lang.Class.isInstance method should work:

if (c.isInstance(obj)) {
...
}

Ken
 
N

natG

Thank you all who replied.

I should have mentioned that I need it to return true, if 'c' (the Class
parameter) is passed an Interface, and obj (the first parameter) implements it.

Therefore, I would assume that c.isInstance would do the trick.

Correct?

Thank you all,
-nat
 
J

Jorn W Janneck

Skippy said:
if(obj.getClass().toString().equals(c.toString()))

that won't do, as two different classes might have the same class name, even
the same fully qualified one.
or maybe (don't know) :

if(object.getClass() == c)

that should work, but using equals seems more robust.

-- j
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top