简体   繁体   中英

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.

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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM