您的位置:首页 > 其它

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

2016-08-29 17:03 375 查看
之前写过的理论博客: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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  反射
相关文章推荐