Java Proxy.newProxyInstance简单动态代理

定义接口

public interface Student
{
	 void buy();

	 String talk();
}

实现类

public class Lisi implements Student
{
	@Override
	public void buy()
	{
		System.out.println("买");
		
	}

	@Override
	public String talk()
	{
	    System.out.println("说");
            return "说"
	}
}

代理类 实现InvocationHandler

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

public class MyInvocation implements InvocationHandler
{
	private Object obj;

	public MyInvocation(Object obj)
	{
		this.obj = obj;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
	{
            if (method.getName().equals("talk"))
            {
                System.out.println("增强方法");
                method.invoke(obj, args);
                return "说";
            }
            method.invoke(obj, args);
            return null;
		
	}

}

测试

import java.lang.reflect.Proxy;

public class Test
{
	public static void main(String[] args)
	{
		Lisi s=new Lisi();
		
		MyInvocation my=new MyInvocation(s);
		
		Student lisi= (Student) Proxy.newProxyInstance(s.getClass().getClassLoader(), s.getClass().getInterfaces(), my);
            //参数一:Lisi类的类加载器
            //参数二:Lisi实现的所有接口
            //参数三:实现了invocationHandler接口的对象
		
		lisi.buy();
		System.out.println(lisi.talk());
	}
}

Java Proxy.newProxyInstance简单动态代理_第1张图片

你可能感兴趣的:(Java)