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

之前写过的理论博客: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

阅读更多
版权声明:本文为博主原创文章,若要转载请注明出处!^_^ https://blog.csdn.net/u010892841/article/details/52354765
文章标签: 反射
个人分类: 反射
上一篇多线程中并发问题
下一篇反射の从Class建立对象
想对作者说点什么? 我来说一句

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

关闭
关闭