spring技术手册上的一个java动态代理例子

public interface IHello {
	public void hello(String name);
}

 

 

public class HelloImpl implements IHello{

	@Override
	public void hello(String name) {
		System.out.println("Hello:" + name);		
	}
}

 

 

 

package proxy;

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

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class LogHandler implements InvocationHandler {
	
	private Logger logger = Logger.getLogger(this.getClass().getName());
	
	private Object delegate;
	
	public Object bind(Object delegate) {
		this.delegate = delegate;
		return Proxy.newProxyInstance(delegate.getClass().getClassLoader(), delegate.getClass().getInterfaces(), this);
	}
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)	throws Throwable {
		Object result = null;
		log("method starts..." + method);
		result = method.invoke(delegate, args);
		logger.log(Level.INFO,"methods ends ..." + method);
		return result;
	}
	
	private void log(String message) {
		logger.log(Level.INFO,message);
	}
	
	public static void main(String[] args) {
		LogHandler logHandler = new LogHandler();
		IHello helloProxy = (IHello)logHandler.bind(new HelloImpl());
		helloProxy.hello("ssssssssssssss");
	}

}

 

你可能感兴趣的:(java,apache,spring,log4j)