java 动态代理简单实现

dynamicproxy.service.HelloService

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();

	}

}

 

 

你可能感兴趣的:(java,handler,proxy,dynamic,service)