Java - 是否有一个“子类”?像实例?
我重写了 equals() 方法,我需要知道该对象是否是 Event 子类的实例(Event 是超类)。我想要类似“obj subclassof Event”的东西。这是怎么做到的呢?
提前致谢!
Im overriding an equals() method and I need to know if the object is an instance of a Event's subclass (Event is the superclass). I want something like "obj subclassof Event". How can this be made?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
instanceof
可以很好地处理这个问题。instanceof
can handle that just fine.使用以下代码,您可以检查对象是否是扩展 Event 的类,但本身不是 Event 类实例。
默认情况下,
instanceof
检查对象是否属于任何事件级别的指定类或子类(扩展或实现)。With the following code you can check if an object is a class that extends Event but isn't an Event class instance itself.
By default
instanceof
checks if an object is of the class specified or a subclass (extends or implements) at any level of Event.确实
instanceof
应该足够好,但如果你想确定该类确实是一个子类,那么你可以这样提供检查:由于 Adrian 比我领先一点,我也会添加一种可以使用通用方法来执行此操作的方法。
通过以下方式使用它:
Really
instanceof
ought to be good enough but if you want to be sure the class is really a sub-class then you could provide the check this way:Since Adrian was a little ahead of me, I will also add a way you could do this with a general-purpose method.
Use this by:
您可能想查看 someObject.getClass().isAssignableFrom(otherObject.getClass());
You might want to look at
someObject.getClass().isAssignableFrom(otherObject.getClass());
Java中没有直接的方法来检查子类。
instanceof Event
将为任何子类对象返回 true您可以在该对象上执行
getClass()
,然后使用getSuperclass()
方法Class
对象来检查超类是否为Event
。There is no direct method in Java to check subclass.
instanceof Event
would return back true for any sub class objectsThe you could do
getClass()
on the object and then usegetSuperclass()
method onClass
object to check if superclass isEvent
.如果 obj 是 Event 的子类,那么它是一个 instanceof。 obj 是它派生的每个类/接口的实例。所以至少所有对象都是 Object 的实例。
If obj is a subclass of Event then it is an instanceof. obj is an instanceof every class/interface that it derives from. So at the very least all objects are instances of Object.