[JAVA] 动态代理代码示例

MyHandler.java

package info.tozzger.demo;

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

public class MyHandler implements InvocationHandler {
	private Object obj;
	private Runnable r;

	private MyHandler(Object obj, Runnable r) {
		super();
		this.obj = obj;
		this.r = r;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		r.run();
		return method.invoke(obj, args);
	}

	public static Object getProxy(Object target, Runnable runnable) {
		return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),
				new MyHandler(target, runnable));
	}

}

例子:

Talkable.java

package info.tozzger.demo;

public interface Talkable {
	void say();
}

Person.java

package info.tozzger.demo;

public class Person implements Talkable {
	String name;

	public Person(String name) {
		this.name = name;
	}

	@Override
	public void say() {
		System.out.printf("I'm %s.%n", name);
	}
}

Demo.java

package info.tozzger.demo;

public class Demo {

	public static void main(String[] args) {
		Person p = new Person("小明");
		Talkable proxy = (Talkable) MyHandler.getProxy(p, () -> System.out.println("HELLO"));
		proxy.say();
		/*
		 * HELLO
		 * I'm 小明.
		 */
	}

}

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注