How to find the specific implementation class in Java with multiple implementations?

In Java, you can use the instanceof operator to determine if an object is an instance of a particular class. If a class implements multiple interfaces, you can loop through all possible implementation classes and then use the instanceof operator to check if the object is an instance of that implementation class.

Here is an example code demonstrating how to find the specific implementation class:

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() {
        // ...
    }
}

In the code above, the MyInterface interface has two implementations: MyImplementation and MyOtherImplementation. By using the instanceof operator, we can determine which specific implementation class obj object belongs to and then perform the corresponding operation.

bannerAds