java对于接口和抽象类的代理实现,不需要有具体实现类

原文链接: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实现就可以使用这种方式了。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值