[英]how do I tell if a class is equal to or extends another class (java)
所以我正在编写一个Minecraft mod,其中我成功添加了一个手枪,它可以处理各种支持类,可以处理光线跟踪和声音以及GUI叠加等内容。 当手枪工作完美时,我想添加对其他mod的支持,使用我的武器类作为基类添加自己的武器。 我的问题是如何让我的支持类知道一个item类实际上是一个扩展我的武器类的自定义类。 基本上我需要知道的是,是否可以使用我的武器的基础数据和函数将类的实例强制转换为我的武器类进行处理(请注意,我获得了WeponItem类扩展的Item类的实例) 。 有谁知道这样做的好方法?
if(object instanceof SomeClass)
您可以使用instanceof来检查您的类型。
以下示例可以帮助您
class InstanceofDemo {
public static void main(String[] args) {
Parent obj1 = new Parent();
Parent obj2 = new Child();
System.out.println("obj1 instanceof Parent: "
+ (obj1 instanceof Parent));
System.out.println("obj1 instanceof Child: "
+ (obj1 instanceof Child));
System.out.println("obj1 instanceof MyInterface: "
+ (obj1 instanceof MyInterface));
System.out.println("obj2 instanceof Parent: "
+ (obj2 instanceof Parent));
System.out.println("obj2 instanceof Child: "
+ (obj2 instanceof Child));
System.out.println("obj2 instanceof MyInterface: "
+ (obj2 instanceof MyInterface));
}
}
class Parent {}
class Child extends Parent implements MyInterface {}
interface MyInterface {}
Output:
obj1 instanceof Parent: true
obj1 instanceof Child: false
obj1 instanceof MyInterface: false
obj2 instanceof Parent: true
obj2 instanceof Child: true
obj2 instanceof MyInterface: true
参考例子。
instanceOf应该帮助你做到这一点。
if(yourObject instanceof OtherClass)
如果您有一个未知类的对象,您还可以在该对象上使用.getClass()来查找该类。 您还可以比较两个这样的对象:
if(yourObject instanceof OtherObject)
还有一些你应该注意的事项: http : //www.javapractices.com/topic/TopicAction.do?Id=31
您可以检查类是否是基类的实例:
if (objA instanceof baseObj){
// objA is instance of baseObj
}
你可以这样做
Pistol pistol = new Pistol ();
if(pistol instanceof Weapon )
请注意:你真的不应该这样做。 您应该定义一个名为Weapon的接口,然后所有武器必须实现,然后包含程序所需的所有方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.