【问题标题】:How to determine if an inner class implements an interface?如何确定内部类是否实现了接口?
【发布时间】:2022-01-22 23:40:16
【问题描述】:

我有这个代码:

public class test{

    private testInterface i1;

    public test(testInterface i1) {
        this.i1 = i1;
   
    }
     test() {
    }
   

    interface testInterface {
    
        }

 class inner1 implements testInterface {

    }
 class inner2 implements testInterface {

    }
 class inner3 implements testInterface {

    }

     public void determineClass_Interfac(){
      }
}

public class main {

    public static void main(String[] args) {
        test test1 =new test(new test().new inner1());
    }
}

我不知道这是否可行,但我想要实现的是通过调用方法 determineClass_Interfac() 来确定创建了哪个内部类对象。因此,它应该依赖于在类构造函数中创建的对象(这里是 innerClass1)。 我的方法可能完全错误,我只是在这里试验。

【问题讨论】:

  • 这里的目标是什么?假设你发现了,有什么用?
  • 使用 instanceof 操作符。
  • 如果您只需要知道某个内部(或其他)类是否实现了接口,您可以使用instanceof。例如:inner1 test1 = new test().new inner1(); System.out.println(test1 instanceof testInterface);

标签: java class interface inner-classes


【解决方案1】:

您可以使用instanceof 运算符来了解特定实例是否正在实现特定接口或类。

所以代码

public interface MyInterface { 
   ...
}

public class MyInterfaceImpl implements MyInterface {
   ...
}

你可以检查一下

MyInterface myInterface = new MyInterfaceImpl();
if (myInterface instanceof MyInterface) {
     // It goes here because myInterface object is of type MyInterfaceImpl implementing the MyInterface
}

MyInterfaceImpl myInterfaceImpl = new MyInterfaceImpl();
if (myInterfaceImplinstanceof MyInterface) {
     // Also now you go in the if because the runtime type of myInterfaceImpl
     // is implementing your interface
}

这种方法适用于任何类型的类和接口。该类是否为内部类并不重要。


我也给你一些提示:

  • 为方法和类使用有意义的名称
  • 类和接口的名称使用大写
  • 如果您需要从外部类的上下文之外实例化嵌套类,您可能应该对嵌套类使用静态。
  • determineClass_Interfac 方法应将您要测试的对象作为参数。

【讨论】:

  • 你是对的......内部阶级是错误的词。嵌套类更好。如果您需要在容器类的任何现有实例之外实例化该类,则需要将其创建为静态。
  • @user16320675 我更新了答案
猜你喜欢
  • 2013-02-14
  • 2010-10-04
  • 1970-01-01
  • 2012-08-22
  • 1970-01-01
  • 2011-06-25
  • 1970-01-01
  • 2016-09-29
相关资源
最近更新 更多