简体   繁体   中英

Implement interface other than from class signature

Let's say, for example, that I wanted to group some classes in a jar library that all fit the definition of my custom interface. Since I can't edit the classes inside the jar in order to implement my interface, is there any other way to use these classes as though they implemented my interface?

Example: I have uneditable classes A and B . I have a static method in a different class that accepts objects belonging to my interface I . How can I pass in A and B objects without making the method accept all Object objects. I want to give A and B new functionality that only they can have.

Use Adapter design pattern https://en.wikipedia.org/wiki/Adapter_pattern . Create a wrapper over a class from the library, make the wrapper implement your interface, make wrapper use methods of the class.

From your edit and based on my comment: create a class that will implement your interface I and serve as wrapper for classes A and B. This is Facade Design Pattern . Here's a pretty basic simple example in code:

public interface I {
    void methodFromExternalAClass();
    void methodFromExternalBClass();
}

public class MyClass implements I {
    @Override
    public void methodFromExternalAClass() {
         new A().someMethod();
    }
    @Override
    public void methodFromExternalBClass() {
         new B().someMethod();
    }
}

If what you want is to identify whether a given class is in a grouping of classes, similar to using a tagging interface, you could keep a list of Class objects and refer to that list to see if a particular class is in your grouping of classes. If that's not what you want than please clarify. I would comment for clarification, but I don't have the reputation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM