利用反射操作对象的成员和方法

之前写过的理论博客:http://blog.csdn.net/u010892841/article/details/51596392

一个Student对象

一个BeanUtil类用来完成利用反射操作Student对象的成员变量赋值和调用其setter方法。

StudentTest类是程序入口。

<span style="font-size:18px;">package reflect;


public class Student {
	private String name;
	
	private String hobby;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getHobby() {
		return hobby;
	}

	public void setHobby(String hobby) {
		this.hobby = hobby;
	}

	public Student(String name, String hobby) {
		super();
		this.name = name;
		this.hobby = hobby;
	}

	public Student() {
		super();
	}
	
	
	
}
</span>

<span style="font-size:18px;">package reflect;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Date;
import java.util.Map;
import java.util.logging.Logger;

/*
 * @author:qiao pan ma 
 * @time:2016-8-29 16:08:38
 * @a util that can reflect the getter method of a class
 * */
public class BeanUtil {
	/*
	 * create a getter method according to the class name and the data that the getter method needs
	 * */
	public static Object getBean(Map<String, Object> data,String className) throws Exception{
		Class clz=Class.forName(className);
		Object bean=clz.newInstance();
		for(String key:data.keySet()){
			//acquire the name of setter()
			String setter=String.format("set%s%s", key.substring(0, 1).toUpperCase(),key.substring(1));
			//get the value of setter()
			Object value=data.get(key);
			
			/*get the Method Object according to the method name 
			 * and the type of parameters(can get from the Object.getClass)
			*/
			try {
				Method method=clz.getMethod(setter, value.getClass());
				//the condition is that method must be public
				if(Modifier.isPublic(method.getModifiers())){
					method.invoke(bean, value);
				}
			} catch (NoSuchMethodException e) {
				Logger.getLogger(BeanUtil.class.getName()).warning(String.format("没有   %s 方法", setter));
			}
		}
		return bean;
		
	}
}
</span>

<span style="font-size:18px;">package reflect;

import java.util.HashMap;
import java.util.Map;

import org.junit.experimental.theories.Theories;

public class TestStudent {
	public static void main(String[] args) throws Exception {
		Map<String, Object> data=new HashMap<String, Object>();
		data.put("name", "Qiao");
		data.put("hobby", "travelling");
		
		Student student=(Student)BeanUtil.getBean(data, "reflect.Student");
		
		System.out.println("the hobby of "+student.getName()+" is "+student.getHobby());
		//System.out.printf("(%s, %d)%n", student.getName(),student.getHobby());
	}
}
</span>
执行的结果是    the hobby of Qiao is travelling

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值