Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java instanceof with changing objects

I need a method where i could pass on a parameter which i assume would be a Class (not sure though) and in that method, instanceof would be used to check if x is an instance of the passed Class.

How should i do that? I tried a few things but none worked.

like image 739
Nicolas Martel Avatar asked Oct 07 '12 04:10

Nicolas Martel


2 Answers

How about this:

public boolean checker(Object obj) {
    return obj instanceof SomeClass;
}

or if SomeClass needs to be a parameter:

public boolean checker(Object obj, Class someClass) {
    return someClass.isInstance(obj);
}

or if you want the instance to be someClass and NOT an instance of a subclass of someClass:

public boolean checker(Object obj, Class someClass) {
    return someClass.equals(obj.getClass());
}
like image 158
Stephen C Avatar answered Nov 10 '22 23:11

Stephen C


Use Class.isInstance(Object).

like image 42
nneonneo Avatar answered Nov 11 '22 00:11

nneonneo