Cannot override method and cannot access field while using idiom “Providing a default interface implementation”

时光怂恿深爱的人放手 提交于 2019-12-24 08:56:20

问题


Here is code:
IDefaultInterface.aj:

public interface IDefaultInterface {
    public void m1();   
    static aspect Impl{
        public int f1;
        public void IDefaultInterface.m1(){

        }
    }
}

DefaulstInterfaceClass.java:

public class DefaultInterfaceClass implements IDefaultInterface {

    @Override
    public void m1() {

    }

    void mm() {

        f1 = 9;
    }
}

In the second piece of code I'm trying to override m1() method and access f1 field. The compiler allows neither one.
How to overcome these limitations?

Additional thoughts. I would not wonder so much if in "AspectJ in action" 2 edition wasn't said about using this idiom that effect should be the same "as extending the default implementation for both (if multiple inheritance was allowed in Java)." I believe that multiple inheritance associated with C++ for majority. So, why not provide the semantics to which people used to?


回答1:


I'm not fluent in AspectJ, but I see a couple of questionable things: your aspect is trying to define a non-abstract method in an interface, and your class is trying to access field f1 as if it owns the field, when you've declared f1 on the aspect. I'm not quite sure what you're trying to do here, but I don't think you're going about it in the right way.




回答2:


First of all I misspelled f1 declaration. It should be

public int IDefaultInterface.f1;

It solves access field problem.

The second problem is solved by using following code:

public interface IDefaultInterface {
public void m1();   
public static interface Impl extends IDefaultInterface{
    static aspect Implementation{
        public int IDefaultInterface.Impl.f1;
        public void IDefaultInterface.Impl.m1(){

        }

    }
}
}

And then:

 public class DefaultInterfaceClass implements IDefaultInterface.Impl ....


来源:https://stackoverflow.com/questions/7139924/cannot-override-method-and-cannot-access-field-while-using-idiom-providing-a-de

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!