类反射 模拟Java内省的功能

来源:互联网 发布:linux 鸟哥的私房菜 编辑:程序博客网 时间:2024/06/05 08:58

在学习了类反射之后,模拟了一下java内省的功能。

★ 准备工作 

定义一个Model类,里面所有的属性都是private的,然后为每个属性提供getter和setter方法;
再准备一个Map,map的key值都是类里面的属性字段的字符串表示,值任意。 

★ 真正的工作 

设计一个方法Object getModel(Map map,Class cls),传入一个包含所有值的Map,然后再传入Model类的class,那么返回Model类的实例,这个实例里面已经包含好了所有相关的数据。也就是把Map中的数据通过反射,设置回到Model类实例中。 

package cn.hncu.reflect.beanUtils;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.Map;/** * @author<a href="mailto:794530831@qq.com">dragon_Dai</a> * @version 2017-8-19 上午1:07:39 * @filename MyBeanUtils.java *  * 模拟java内省的功能 */public class MyBeanUtils {//public static <E> E populate(Class<E> c,Map<String, Object> map) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException{E obj=c.newInstance();//获取c中的所有Field对象Field[] fields=c.getDeclaredFields();//针对每一个Field对象,如果map中有该属性,就对该就通过其setter()方法进行设置值.否则就自动跳过for(Field field:fields){Object value=map.get(field.getName());if(value==null){//说明map中没有该属性System.out.println("map中没有"+field+"属性");continue;}else{//说明map中有该属性//例如: 把age属性 变成 setAge(int age)方法String name="set"+field.getName().substring(0, 1).toUpperCase()+field.getName().substring(1);Class parameterTypes=field.getType();//方法的参数Method m=c.getDeclaredMethod(name, parameterTypes);m.invoke(obj, value);//相当于 obj.setAge(value);}}return obj;}}

BookModel:

package cn.hncu.reflect.beanUtils;import java.io.Serializable;public class BookModel implements Serializable {private String uuid;private String name;private double inPrice;private double salePrice;public String getUuid() {return uuid;}public void setUuid(String uuid) {this.uuid = uuid;}public String getName() {return name;}public void setName(String name) {this.name = name;}public double getInPrice() {return inPrice;}public void setInPrice(double inPrice) {this.inPrice = inPrice;}public double getSalePrice() {return salePrice;}public void setSalePrice(double salePrice) {this.salePrice = salePrice;}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + ((uuid == null) ? 0 : uuid.hashCode());return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;BookModel other = (BookModel) obj;if (uuid == null) {if (other.uuid != null)return false;} else if (!uuid.equals(other.uuid))return false;return true;}@Overridepublic String toString() {return uuid + ",《" + name + "》,进价:" + inPrice + "元, 售价:" + salePrice+"元";}}
测试

package cn.hncu.reflect.beanUtils;import java.lang.reflect.InvocationTargetException;import java.util.HashMap;import java.util.Map;public class Test {@org.junit.Testpublic void testMyBeanUtils(){Class<BookModel> c=BookModel.class;Map<String, Object> map=new HashMap<String, Object>();map.put("uuid", "1");map.put("name", "java");map.put("inPrice", 13.3);try {BookModel book = MyBeanUtils.populate(c, map);System.out.println("book:"+book);} catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (NoSuchMethodException e) {e.printStackTrace();} catch (SecurityException e) {e.printStackTrace();} catch (IllegalArgumentException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();}}}
结果:

map中没有private double cn.hncu.reflect.beanUtils.BookModel.salePrice属性book:1,《java》,进价:13.3元, 售价:0.0元

原创粉丝点击