java 动态代理简单实现_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > java 动态代理简单实现

java 动态代理简单实现

 2014/8/19 3:22:36  antlove  程序员俱乐部  我要评论(0)
  • 摘要:dynamicproxy.service.HelloServicepackagedynamicproxy.service;publicinterfaceHelloService{publicvoidsayHello();}dynamicproxy.service.impl.HelloServiceImplpackagedynamicproxy.service.impl;importdynamicproxy.service.HelloService
  • 标签:实现 Java 代理

dynamicproxy.service.HelloService

class="java">package dynamicproxy.service;

public interface HelloService {
	public void sayHello();
}

?

dynamicproxy.service.impl.HelloServiceImpl

package dynamicproxy.service.impl;

import dynamicproxy.service.HelloService;

public class HelloServiceImpl implements HelloService {

	@Override
	public void sayHello() {
		System.out.println("hello everyone ... ");

	}

}

?

dynamicproxy.handler.LogHandler

package dynamicproxy.handler;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class LogHandler implements InvocationHandler {

	private Object target = null;
	
	public LogHandler(Object target) {
		this.target = target;
	}

	private void doBefore(){
		System.out.println("do before ... ");
	}
	
	private void doAfter(){
		System.out.println("do after ... ");
	}
	
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
	
		doBefore();
		
		Object res = method.invoke(target, args);
		
		doAfter();
		
		return res;
	}

}

?

dynamicproxy.test.Main

package dynamicproxy.test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

import dynamicproxy.handler.LogHandler;
import dynamicproxy.service.HelloService;
import dynamicproxy.service.impl.HelloServiceImpl;

public class Main {

	public static void main(String[] args) {
		HelloService target = new HelloServiceImpl();
		
		InvocationHandler handler = new LogHandler(target);
		
		HelloService helloService = (HelloService) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), handler);
		
		helloService.sayHello();

	}

}

?

?

上一篇: 处理异常方式 下一篇: 没有下一篇了!
  • 相关文章
发表评论
用户名: 匿名