简体   繁体   English

向实现接口的所有类添加方法

[英]Adding a method to all classes that implement an interface

There are several classes (which I can't edit) which implement an interface, is it possible to add a method that only calls methods defined in the interface to each class that implements that interface? 有几个实现接口的类(我无法编辑),是否可以向实现该接口的每个类中添加仅调用接口中定义的方法的方法?

(without java 8) (没有Java 8)

No, I don't believe so. 不,我不相信。 Such a method would have to realized in the concrete class as a real method, but without access to the classes themselves you can't do that. 这样的方法必须在具体的类中实现为真正的方法,但是如果没有访问类本身的权限,则无法这样做。

You might create subclasses of each, and all those subclasses could implement you new interface with the new method. 您可以为每个子类创建子类,所有这些子类都可以使用新方法实现新的接口。

我不确定我是否正确,但是如果类A,B,C,...实现了接口I,并且您无法编辑A,B,C ...,并且想要添加一个方法,那么您可以用新的子类扩展每个类,每个subA,subB,subC等都可以实现新方法...

I don't think there is a way to do what you are asking, not without resorting to byte code manipulation anyway. 我认为没有一种方法可以解决您所要问的问题,无论如何都不能不依靠字节码操作。

Perhaps AOP would help, you could add a point cut to the target methods of the interface. 也许AOP会有所帮助,您可以在接口的目标方法上添加切入点。

If you are using Java 8 and can modify the interface, then yes: 如果您使用的是Java 8,并且可以修改接口,则可以:

interface Face {
    Object existing();

    default Object additional() {
        return "Hello " + existing() + "!";
    }
}

Otherwise, no, you cannot. 否则,您不能。 Java does not have a feature like Javascript prototypes, C# extension methods, etc at this time. Java目前没有Javascript原型,C#扩展方法等功能。

Just write a static method that takes in the interface type and calls the methods: 只需编写一个采用接口类型并调用方法的static方法:

interface Fooable
{
    void foo();
}


public class FooableExtensions
{
    public static void doSomethingToFooable( Fooable f /*, other parameters*/ )
    {
        f.foo();
    }
}

It doesn't have the fancy syntactic-sugar that C# extension methods provide, but it should do the trick. 它没有C#扩展方法提供的精美的语法糖,但是应该可以解决问题。

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

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