Const interface to complex objects
如秃子老大指出,当从 getter method 返回 mutable object 时总会“心惊胆战”,因为 Java 没有提供一种语法上的强制措施保证返回的引用不会被用于修改对象本身的属性。余尝求解于此。
public I getImmutable() {
return (I)Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] {I.class}, new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().startsWith("set")) {
throw new UnsupportedOperationException("Unmodifiable");
}
return method.invoke(proxy, args);
}
});
}
方案是基于 setXXX 的命名习惯,且所有 setXXX 均须来自某 interface,因此基本算是。。完全没有意义。:(
另外一种方法是纯粹的手工操作
public Immutable getImmutable() {
return new Immutable() {
@Override
public void setI(int i) {
throw new UnsupportedOperationException("Unmodifiable");
}
// 一一添加其它需要禁用的方法
};
}
16日凌晨失眠乱写于此。