为了避免类的每个方法中存在的“肮脏”,如果你的类实现了一个公共接口,你可以使用 a来执行与你实现方法本身不同Proxy
的公共设置。invokeAndWait
- 实现一个 Proxy InvocationHandler来处理所有样板代码以检查事件调度线程并调用
invokeAndWait
- 创建代理的实例并在其上调用方法,而不是直接在您的实现类上。
由于这种方法包含更多的代码,因此仅当您的实现类有大量您希望确保在 EDT 上运行的方法时才适用。
完整示例:
public class ImplClass implements ClassInterface {
public void a( String paramA, int paramB ) {
// do something here...
}
}
public interface ClassInterface {
void a( String paramA, int paramB );
}
public class MyHandler implements InvocationHandler {
private ClassInterface implClassInstance;
public MyHandler( ImplClass implInstance ) {
this.implClassInstance = implInstance;
}
public Object invoke( Object proxy, final Method method, final Object[] args ) throws Throwable {
if( SwingUtilities.isEventDispatchThread() ) {
method.invoke( implClassInstance, args );
}
else {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
try {
method.invoke( implClassInstance, args );
}
catch( RuntimeException e ) {
throw e;
}
catch( Exception e ) {
throw new RuntimeException( e );
}
}
} );
}
return null;
}
}
以下是使用代理的方法:
// create the proxy like this:
ImplClass implInstance = new ImplClass();
MyHandler handler = new MyHandler(implInstance);
ClassInterface proxy = (ClassInterface) Proxy.newProxyInstance( this.getClass().getClassLoader(), new Class[] { ClassInterface.class }, handler );
// ...
// call the proxy like you would an instance of your implementation class
proxy.a( "paramAValue", 123 );