原文链接:http://www.javaarch.net/jiagoushi/835.htm
java对于接口和抽象类的代理实现,不需要有具体实现类
在某些场景下,可能我们只需要定义接口或者抽象类,而具体实现或者可以从接口的annotation就可以知道具体实现,后者具体实现由其他动态语言实现,或者需要实现AOP的一些其他功能,我们不需要具体实现,那么我们有哪些方法可以来实现这样的功能呢?
1.使用java.lang.reflect.Proxy代理类
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyTest {
public static void main(String[] args) {
ClassLoader cl = ProxyTest.class.getClassLoader();
Class[] interfaces = new Class[]{ ActionListener.class };
Object object = Proxy.newProxyInstance(cl, interfaces, new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String name = method.getName();
if(name.equals("toString")) {
return "toString was called";
}
else if(name.equals("actionPerformed")) {
System.out.println("actionPerformed was called");
return null;
}
throw new RuntimeException("no method found");
}
});
((ActionListener) object).actionPerformed(null);
}
}
输出:
actionPerformed was called
2.通过javassist的javassist.util.proxy.ProxyFactory来实现
public class Test {
public static void main(String[] args) throws Exception {
ProxyFactory factory = new ProxyFactory();
factory.setInterfaces(new Class[] { ActionListener.class });
factory.setHandler(new MethodHandler() {
public Object invoke(Object arg0, Method method, Method arg2, Object[] arg3) throws Throwable {
String name = method.getName();
if(name.equals("toString")) {
return "toString was called";
}
else if(name.equals("actionPerformed")) {
System.out.println("actionPerformed was called");
return null;
}
throw new RuntimeException("no method found");
}
});
Class c = factory.createClass();
Object object = c.newInstance();
((ActionListener) object).actionPerformed(null);
}
}
这里主要的不同是factory.setSuperclass(MouseAdapter.class);这是设置抽象类接口
对于之前我们描述的http://blog.csdn.net/zhongweijian/article/details/8475086 利用spring AOP和Annotation来简化DAO实现就可以使用这种方式了。