本文共 1109 字,大约阅读时间需要 3 分钟。
1.1.1 功能分析
定义MyBeanUtils工具类, 实现与BeanUtils相同的功能public static void setProperty(Object bean,String name,Object value)// 设置任意对象的, 任意属性, 为任意的值public static String getProperty(Object bean,String name)// 获取任意对象的任意属性public static void populate(Object bean,Map map)// 修改任意对象中的属性, 为传入Map集合中的键和值Ps: 下个知识点1.1.2 实例代码package com.itheima_03;import java.lang.reflect.Field;public class MyBeanUtils {private MyBeanUtils() {}//public static void setProperty(Object bean,String name,Object value)public static void setProperty(Object bean,String name,Object value) throws ReflectiveOperationException {//根据JavaBean对象获取对应的字节码对象Class clazz = bean.getClass();//根据字节码对象获取对应的Field对象Field f = clazz.getDeclaredField(name);//设置权限,让虚拟机不进行访问的检查f.setAccessible(true);//赋值f.set(bean, value);}//public static String getProperty(Object bean,String name)public static String getProperty(Object bean,String name) throws ReflectiveOperationException {Class clazz = bean.getClass();Field f = clazz.getDeclaredField(name);f.setAccessible(true);Object obj = f.get(bean);return obj.toString();}}
转载于:https://blog.51cto.com/13587708/2374103