[英]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. 我正在尝试在类中创建一个方法,该方法将Class
作为参数,并检查当前对象是否属于该类型。 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. 也许我对“ Class
”班级的理解不正确。
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. 对不起。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.