详解Java的getInterfaces()方法:返回该类所实现的所有接口的数组

  • Post category:Java

Java中getInterfaces()方法用于获取当前类或接口直接实现的所有接口的class对象。

方法签名

public Class<?>[] getInterfaces()

返回值

方法会返回一个数组,其中包含了当前类或接口直接实现的所有接口的class对象。如果当前类或接口没有实现任何接口,则返回一个长度为0的数组。

示例 1

public interface Animal {
    void run();
}

public class Dog1 implements Animal {
    @Override
    public void run() {
        System.out.println("Dog1 is running...");
    }
}

public class Dog2 implements Animal {
    @Override
    public void run() {
        System.out.println("Dog2 is running...");
    }
}

public class Test {
    public static void main(String[] args) {
        Dog1 dog1 = new Dog1();
        Dog2 dog2 = new Dog2();

        Class<? extends Dog1> dog1Clazz = dog1.getClass();
        Class<? extends Dog2> dog2Clazz = dog2.getClass();

        Class<?>[] dog1Interfaces = dog1Clazz.getInterfaces();
        Class<?>[] dog2Interfaces = dog2Clazz.getInterfaces();

        System.out.println("Dog1 Interfaces:");
        for (Class<?> dog1Interface: dog1Interfaces) {
            System.out.println(dog1Interface.getName());
        }

        System.out.println("Dog2 Interfaces:");
        for (Class<?> dog2Interface: dog2Interfaces) {
            System.out.println(dog2Interface.getName());
        }
    }
}

在该示例中,我们定义了两个类Dog1Dog2,它们都实现了Animal接口。Test类中对Dog1Dog2分别实例化并获取它们的Class对象,分别调用了getInterfaces()方法,并通过遍历数组获取它们直接实现的接口。最终输出了Dog1Dog2直接实现的接口信息。

示例 2

public interface Run {
    void run();
}

public interface Jump {
    void jump();
}

public interface Swim {
    void swim();
}

public class Animal implements Run, Jump {
    @Override
    public void run() {
        System.out.println("Animal is running...");
    }

    @Override
    public void jump() {
        System.out.println("Animal is jumping...");
    }
}

public class Duck extends Animal implements Swim {
    @Override
    public void swim() {
        System.out.println("Duck is swimming...");
    }
}

public class Test {
    public static void main(String[] args) {
        Duck duck = new Duck();
        Class<? extends Duck> duckClazz = duck.getClass();
        Class<?>[] duckInterfaces = duckClazz.getInterfaces();

        System.out.println("Duck Interfaces:");
        for (Class<?> duckInterface: duckInterfaces) {
            System.out.println(duckInterface.getName());
        }
    }
}

在该示例中,我们定义了三个接口RunJumpSwim,其中RunJump都被Animal类实现。Duck类继承了Animal类并实现了Swim接口。Test类中对Duck实例进行了Class对象的获取并调用了getInterfaces()方法,并通过遍历数组获取它们直接实现的接口。最终输出了Duck直接实现的接口信息。

希望这个完整攻略能够帮到你。