【问题标题】:Get parent interface of interface in Java [duplicate]在Java中获取接口的父接口[重复]
【发布时间】:2014-06-03 16:34:33
【问题描述】:

我需要递归遍历给定对象的所有接口和超类。当父类是另一个类时,这很好用,但是当一个接口扩展另一个接口时,我得到一个 NullPointerException。

这是一个例子:

public class Test {

    private interface Foo {

    }

    private interface Bar extends Foo {

    }

    public static void main(String args[]) {
        System.out.println(Bar.class.getSuperclass().getSimpleName());
    }
}

这会抛出 NullPointerException 而不是按预期打印 Foo。有没有办法获取接口的超类?

【问题讨论】:

    标签: java class interface


    【解决方案1】:

    使用

    Bar.class.getInterfaces()

    获取Bar实现的接口。

    更新

    根据您的需要,您可能需要寻找特定的接口或类:

    酒吧栏 = ...

    if (bar instanceof Foo) {
        System.out.println(true);
    }
    
    // Or
    if (Foo.class.isInstance(bar)) {
        System.out.println(true);
    }
    
    // Or
    if (Foo.class.isAssignableFrom(Bar.class)) {
        System.out.println(true);
    }
    

    【讨论】:

    • +1。即使声明说接口“扩展”了另一个接口,它也不是超类。接口可以“扩展”多个接口。
    • 就是这样 - 谢谢。 extend 和 implement 关键字是如此混乱 - 在泛型中,您使用 extend 来指定接口,然后接口相互扩展,但它们的行为就像它们相互实现一样。
    【解决方案2】:

    很明显,我一发这个就想通了..

    对于其他想知道的人,接口的父接口由getInterfaces() 方法返回。以下将按预期打印Foo

    public class Test {
    
        private interface Foo {
    
        }
    
        private interface Bar extends Foo {
    
        }
    
        public static void main(String args[]) {
            System.out.println(Bar.class.getInterfaces()[0].getSimpleName());
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 2016-10-07
      • 2012-04-10
      • 2018-06-24
      • 2019-05-08
      • 2017-02-28
      • 2018-01-16
      相关资源
      最近更新 更多