public class Bar {
// Third party class -- I don't want to rely on its current interface.
}
public class Foo {
private /* not final */ Bar bar;
public refreshBar() {
bar = new Bar(); // Old references are now "dead".
}
/** Question: The reference this method returns can change. */
public Bar getBar() {
return bar;
}
}
Foo foo = new Foo();
foo.getBar().doThing(); // OK.
Bar bar = foo.getBar(); // BAD - I want this to be forbidden.
bar.doThing(); // ERROR.如何使BAD行在编译时中断?如果不能做到这一点,那么我如何让它抛出异常呢?它甚至会受到影响吗?
发布于 2017-07-01 09:34:22
很简单。不要暴露Bar,只暴露你想要的任何方法:
public class Foo {
private Bar bar;
public refreshBar() {
bar = new Bar();
}
public void doOneThing() {
bar.firstThing();
}
public void doAnotherThing() {
bar.secondThing();
}
}发布于 2017-07-01 09:39:13
下面是一个用于您的目的的简单包装器的演示:
public class BarWrapper {
public static void doThing() {
foo.getBar.doThing();
}
}
public static void Main( String[] Args) {
foo.getBar // ERROR: does not import FOO
BarWrapper.doThing(); // WORKS}
发布于 2017-07-01 09:46:13
如果Bar是一个接口,您可以为该接口创建一个Proxy对象并返回它。然后,当调用该代理接口上的任何方法时,您可以获取当前的Bar对象,并将调用传递给该实例。
请参阅:Proxy文档
https://stackoverflow.com/questions/44856516
复制相似问题