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

使用反射来调用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();
		
		
	}

}



阅读更多
个人分类: java
上一篇J2SE学习笔记:Set集合中相等性的比较,hashCode()与equals()
下一篇J2SE学习笔记:设计模式之工厂模式
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭