以下Test方法中问什么不能掉Set方法?
A cproxy = new CProxy(bimpl);
cproxy指向的是 CProxy类啊? 而Cproxy里面有setAspect(),为什么不能调。。。
interface A{ void say(); } class BImpl implements A{ public void say() { System.out.println("Hello"); } } class CProxy implements A{ private Aspect aspect; private A a; public void setAspect(Aspect aspect) { this.aspect = aspect; } public CProxy(A a) { this.a = a; } public void say() { aspect.start(); a.say(); aspect.end(); } } class Aspect{ public void start() { System.out.println("start()"); } public void end() { System.out.println("end"); } } class Test{ public static void main(String[] args) { A bimpl = new BImpl(); A cproxy = new CProxy(bimpl); Aspect aspect = new Aspect(); //cproxy.setAspect(aspect) } }
因为你是A cproxy,实例化出来的是A的派生实例,你只能看到A接口中暴露出来的方法,但的确在运行时cproxy就是CProxy实例,你可以强转为CProxy或者再接口层面添加对应方法