jdk动态代理简单实现

1.创建student接口

package com.xq.DynamicProgramming;

public interface student {
	void study();
	void play();
}

2.创建studentImpl实现类实现student接口

package com.xq.DynamicProgramming;

public class studentImpl implements student {

	public void study() {
		// TODO Auto-generated method stub
		System.out.println("study..");
	}

	public void play() {
		// TODO Auto-generated method stub
		System.out.println("play..");
	}

}

3.创建myInvocationHandler类实现InvocationHandler

package com.xq.DynamicProgramming;

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

public class myInvocationHandler implements InvocationHandler {
	public Object target;
	public myInvocationHandler(Object target) {
		// TODO Auto-generated constructor stub
		this.target=target;
	}
	
	public Object getInstance(Object target) {
		return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
	}
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		// TODO Auto-generated method stub
		System.out.println("before..");
		method.invoke(target, args);
		System.out.println("after..");
		return null;
	}

}

4.创建测试类test测试功能

package com.xq.DynamicProgramming;

import java.lang.reflect.Proxy;

public class test {
	public static void main(String[] args) throws InstantiationException, IllegalAccessException {
		student stu=new studentImpl();
		stu.study();
		
		System.out.println("--------------------------");
		
		student st=new studentImpl();
		myInvocationHandler m=new myInvocationHandler(st);
		student s=(student) m.getInstance(st);
		s.study();
	}
}

效果如下:

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值