简体   繁体   中英

Checking if class is of certain type

I'm trying to create a method inside a class that will take Class as a parameter and will check if the current object is of that type. The code i have:

public class MyEvent extends MyBPMNNode {

public boolean isKindOf(Class<?> node) {
    boolean b = MyEvent.this instanceof node;
    return b;
}

But i compile it it gives me:

Error:(9, 45) java: cannot find symbol
symbol:   class node

What am i doing wrong here? Maybe my understanding of the ' Class ' class is not right.

You want:

public boolean isKindOf(Class<?> clazz) {
    return clazz.isInstance(this);
}

您可能在node.isAssignableFrom(MyEvent.this)

You are introducing generics for no particular reason. Try this:

    public boolean isKindOf(Object node) {
        // weak
        return node.getClass().isAssignableFrom(getClass());
        // stronger, but not appropriate in your case
        //return this.getClass().equals(node.getClass());
    }

Andy Turner's answer is much more concise. Pardon me.

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