简体   繁体   English

实现除类签名以外的接口

[英]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. 例如,让我说,我想在jar库中对一些完全符合我的自定义界面定义的类进行分组。 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? 由于我无法编辑jar内的类以实现我的接口,是否有其他方法可以像使用它们来实现我的接口一样使用这些类?

Example: I have uneditable classes A and B . 示例:我有不可编辑的类AB I have a static method in a different class that accepts objects belonging to my interface I . 我在另一个类中有一个静态方法,该方法接受属于接口I对象。 How can I pass in A and B objects without making the method accept all Object objects. 如何在不使方法接受所有Object对象的情况下传递AB对象。 I want to give A and B new functionality that only they can have. 我想给AB一个只有他们才能拥有的新功能。

Use Adapter design pattern https://en.wikipedia.org/wiki/Adapter_pattern . 使用Adapter设计模式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 . 从您的编辑中并根据我的评论:创建一个将实现您的接口I并用作类A和B的包装的类。这是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. 如果要确定给定的类是否在类的分组中(类似于使用标记接口),则可以保留“ Class对象的列表,然后引用该列表以查看特定的类是否在类的分组中。 If that's not what you want than please clarify. 如果这不是您想要的,请澄清。 I would comment for clarification, but I don't have the reputation. 我想发表评论以澄清问题,但我没有声誉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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