关闭

J2SE学习笔记:反射与动态代理

437人阅读 评论(0) 收藏 举报
分类:

使用反射来调用PO类的get和set方法:

package cn.itcast.getterandsetter;

public class Person {
	private int id;
	private String name;
	public void setId(int id){
		this.id = id;
	}
	public int getId(){
		return id;
	}
	
	public void  setName(String name){
		this.name = name;
	}
	
	public String getName(){
		return name;
	}

}

package cn.itcast.getterandsetter;

import java.lang.reflect.Method;

public class GetAndSet {
	public static void main(String[] args) throws ClassNotFoundException, Exception, Exception {
		Class<?> c = null;
		//得到Class类的引用
		c = Class.forName("cn.itcast.getterandsetter.Person");
		Object obj = c.newInstance();
		setter(obj,"id",int.class,1);
		getter(obj, "id");
		
		setter(obj,"name",String.class,"lilei");
		getter(obj, "name");
		
		
	}
	//工具类,将属性的首字母变大写,以方便传进getMethod()方法中
	private static String strUtil(String old){
		String str = old.substring(0,1).toUpperCase()+old.substring(1);
		return str;
		
	}
	
	private static void setter(Object obj,String field,
						Class<?> type,Object value) throws Exception{
		Method method = obj.getClass().getMethod("set"+strUtil(field), type);
		
		method.invoke(obj, value);
		
	}
	
	private static void getter(Object obj,String field) throws Exception{
		Method method = obj.getClass().getMethod("get"+strUtil(field));
		System.out.println(method.invoke(obj));
		
	}

}

动态代理:就是讲代理模式的代理类用反射生成:
package cn.cuige.dynamicProxy;

//接口
public interface Homework {
	public void doHomework();

}

package cn.cuige.dynamicProxy;
//真实角色
public class IHomework implements Homework{

	@Override
	public void doHomework() {
		System.out.println("自己在做家庭作业");
		
	}
}

package cn.cuige.dynamicProxy;

//代理角色
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class ProxyMan implements InvocationHandler{
	Object obj = null;
	
	ProxyMan(Object obj){  //在构造中接受一个真实角色
		this.obj = obj;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		method.invoke(obj);
		helpDoHomeWork();
		
		
		
		return null;
	}
	
	private void helpDoHomeWork() {
		System.out.println("代理在帮忙做作业");

	}

}

package cn.cuige.dynamicProxy;
//测试程序
import java.lang.reflect.Proxy;

public class Test {
	public static void main(String[] args) {
		//得到一个真实角色,并得到他的Class对象
		IHomework i = new IHomework();
		Class<?> iclass = i.getClass();
		
		//得到一个InvocationHandler对象
		ProxyMan pm = new ProxyMan(i);
		
		//得到一个Proxy对象
		Homework proxyobj = (Homework)Proxy.newProxyInstance(iclass.getClassLoader(), 
				iclass.getInterfaces(), pm);
		proxyobj.doHomework();
		
		
	}

}



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:18363次
    • 积分:458
    • 等级:
    • 排名:千里之外
    • 原创:26篇
    • 转载:10篇
    • 译文:0篇
    • 评论:0条
    文章分类