Linux 拨号vps windows公众号手机端

java多实现如何找到具体的实现类

lewis 8年前 (2017-04-05) 阅读数 12 #程序编程
文章标签 Java

在Java中,可以使用instanceof运算符来判断一个对象是否是某个类的实例。如果一个类实现了多个接口,可以通过遍历所有可能的实现类,然后使用instanceof运算符来判断对象是否是该实现类的实例。

下面是一个示例代码,演示了如何找到具体的实现类:

public class Main {
    public static void main(String[] args) {
        MyInterface obj = new MyImplementation();

        if(obj instanceof MyImplementation) {
            MyImplementation implementation = (MyImplementation) obj;
            // 找到了 MyImplementation 的实例,可以进行相应的操作
            implementation.doSomething();
        } else if(obj instanceof MyOtherImplementation) {
            MyOtherImplementation otherImplementation = (MyOtherImplementation) obj;
            // 找到了 MyOtherImplementation 的实例,可以进行相应的操作
            otherImplementation.doSomethingElse();
        }
    }
}

interface MyInterface {
    // ...
}

class MyImplementation implements MyInterface {
    // ...
    public void doSomething() {
        // ...
    }
}

class MyOtherImplementation implements MyInterface {
    // ...
    public void doSomethingElse() {
        // ...
    }
}

在上面的代码中,MyInterface接口有两个实现类:MyImplementationMyOtherImplementation。通过使用instanceof运算符,我们可以判断obj对象是哪个具体的实现类的实例,然后进行相应的操作。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门