📄 setproxyexample.java
字号:
import java.lang.reflect.*;import java.util.*;/* * Implement InvocationHandler to turn on and off the ability * to disable the methods in Set that remove elements from the * collection */class DisallowRemoveSet implements InvocationHandler { private Set delegate; private boolean disallowRemove = true; public DisallowRemoveSet(Set delegate) { this.delegate = delegate; } public void setDisallowRemove(boolean disallowRemove) { this.disallowRemove = disallowRemove; } public Object invoke( Object proxy, Method meth, Object[] args ) throws Throwable { if ( disallowRemove && (meth.getName().startsWith("remove") || meth.getName().equals("retainAll") || meth.getName().equals("clear")) ) { // trying to remove when the option is disabled throw new UnsupportedOperationException( "Set does not allow element removal"); } // method call okay, send it on to the delegate Set implementation return meth.invoke(delegate, args); }}public class SetProxyExample { public static void main(String[] args) { Set delegate = new HashSet(); Class[] setInterface = new Class[] { Set.class }; DisallowRemoveSet handler = new DisallowRemoveSet(delegate); // create a proxy that wraps a HashSet implementation of the Set // interface with a DisallowRemoveSet Set setProxy = (Set)Proxy.newProxyInstance( Thread.currentThread(). getContextClassLoader(), setInterface, handler ); // build a set with 5 elements String[] data = new String[] {"A","B","C","D","E"}; setProxy.addAll( Arrays.asList(data) ); try { System.out.println("Enable removes and call for first data entry"); handler.setDisallowRemove(false); setProxy.remove( data[0] ); handler.setDisallowRemove(true); System.out.println("Disable removes and call for second data entry"); setProxy.remove( data[1] ); } catch (UnsupportedOperationException e ) { System.out.println("Exception thrown: " + e.getMessage()); } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -