通过PropertyDescriptor反映射调用set和get方法
2023-06-13 09:14:58 时间
1
package com.zhoushun;
import java.lang.reflect.Method;
import java.lang.reflect.Field;
import java.beans.PropertyDescriptor;
public class PropertyUtil {
@SuppressWarnings("unchecked")
public static PropertyDescriptor getPropertyDescriptor(Class clazz, String propertyName) {
StringBuffer sb = new StringBuffer();//构建一个可变字符串用来构建方法名称
Method setMethod = null;
Method getMethod = null;
PropertyDescriptor pd = null;
try {
Field f = clazz.getDeclaredField(propertyName);//根据字段名来获取字段
if (f!= null) {
//构建方法的后缀
String methodEnd = propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
sb.append("set" + methodEnd);//构建set方法
setMethod = clazz.getDeclaredMethod(sb.toString(), new Class[]{ f.getType() });
sb.delete(0, sb.length());//清空整个可变字符串
sb.append("get" + methodEnd);//构建get方法
//构建get 方法
getMethod = clazz.getDeclaredMethod(sb.toString(), new Class[]{ });
//构建一个属性描述器 把对应属性 propertyName 的 get 和 set 方法保存到属性描述器中
pd = new PropertyDescriptor(propertyName, getMethod, setMethod);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return pd;
}
@SuppressWarnings("unchecked")
public static void setProperty(Object obj,String propertyName,Object value){
Class clazz = obj.getClass();//获取对象的类型
PropertyDescriptor pd = getPropertyDescriptor(clazz,propertyName);//获取 clazz 类型中的 propertyName 的属性描述器
Method setMethod = pd.getWriteMethod();//从属性描述器中获取 set 方法
try {
setMethod.invoke(obj, new Object[]{value});//调用 set 方法将传入的value值保存属性中去
}catch (Exception e){
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public static Object getProperty(Object obj, String propertyName){
Class clazz = obj.getClass();//获取对象的类型
PropertyDescriptor pd = getPropertyDescriptor(clazz,propertyName);//获取 clazz 类型中的 propertyName 的属性描述器
Method getMethod = pd.getReadMethod();//从属性描述器中获取 get 方法
Object value =null ;
try {
value = getMethod.invoke(clazz, new Object[]{});//调用方法获取方法的返回值
} catch (Exception e) {
e.printStackTrace();
}
return value;//返回值
}
}
2
public boolean setValue(Object objSet, Object objGet)
throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, IntrospectionException
{
boolean flag = true;
Field fields[] = objSet.getClass().getDeclaredFields();
String value = "";
String fieldNameGet = "";
List list = new ArrayList();
Field afield[];
int j = (afield = fields).length;
for(int i = 0; i < j; i++)
{
Field field = afield[i];
String fieldName = field.getName();
fieldNameGet = xmlToModel(fieldName);
if(!"error".equals(fieldNameGet))
{
PropertyDescriptor pd = new PropertyDescriptor(fieldNameGet, objGet.getClass());
Method getMethod = pd.getReadMethod();
value = String.valueOf(getMethod.invoke(objGet, new Object[0]));
boolean checkResult = returnMessage.checkValue(value, fieldNameGet);
if(checkResult)
{
PropertyDescriptor pd1 = new PropertyDescriptor(fieldName, objSet.getClass());
Method setMethod = pd1.getWriteMethod();
setMethod.invoke(objSet, new Object[] {
field.getType().getConstructor(new Class[] {
java/lang/String
}).newInstance(new Object[] {
value
})
});
} else
{
flag = checkResult;
}
}
}
return flag;
}
3
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectTest {
public static void main(String[] args) throws Exception {
Class clazz = Class.forName("TaskProvidePropsList");//这里的类名是全名。。有包的话要加上包名
Object obj = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
//写数据
for(Field f : fields) {
PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz);
Method wM = pd.getWriteMethod();//获得写方法
wM.invoke(obj, 2);//因为知道是int类型的属性,所以传个int过去就是了。。实际情况中需要判断下他的参数类型
}
//读数据
for(Field f : fields) {
PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz);
Method rM = pd.getReadMethod();//获得读方法
Integer num = (Integer) rM.invoke(obj);//因为知道是int类型的属性,所以转换成integer就是了。。也可以不转换直接打印
System.out.println(num);
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/187072.html原文链接:https://javaforall.cn
相关文章
- h2下update set字段重复处理拦截器
- 完美解决:针对tensorflow中,tf.logging.set_verbosity(tf.logging.ERROR)问题。
- set 方法是坏味道?
- 【C++ 语言】容器 ( queue 队列 | stack 栈 | priority_queue 优先级队列 | set 集合 | 容器遍历 | map )
- ORA-24172: rule set string.string has errors ORACLE 报错 故障修复 远程处理
- ORA-26879: “SET_ENQUEUE_DESTINATION” directive is not permitted on rules used by XStream outbound server “string” ORACLE 报错 故障修复 远程处理
- ORA-27076: unable to set limit for open files ORACLE 报错 故障修复 远程处理
- ORA-19609: string is from different backup set: stamp string count string ORACLE 报错 故障修复 远程处理
- ORA-48150: error encountered with set current working directory ORACLE 报错 故障修复 远程处理
- ORA-06816: TLI Driver: could not set the SPX SAP address ORACLE 报错 故障修复 远程处理
- ORA-12980: checkpoint option not allowed with SET UNUSED ORACLE 报错 故障修复 远程处理
- SQL Server 存储过程遇到“表 ''#TT'' 没有标识属性无法执行 SET 操作”错误
- mongodb replica set 添加删除节点的2种方法
- mysql用find_in_set代替like搜索提高性能详解数据库
- debian 8.2 + apt-get + mongodb 3.2 + replica set详解大数据
- 功能熟悉Oracle的SET功能,提高工作效率(oracle的set)
- Redis SET:修改篇(redisset修改)
- Redis清空Set的一秒操作(redis清空set)
- MySQL中SET集合的使用方法及注意事项(mysql中set集合)
- MySQL中如何设置变量使用SET语句(mysql 中set变量)
- 红色的设定基于 Redis(set if redis)
- 从Redis中获取Set集合的简单方法(redis获取set集合)
- php中使用session_set_save_handler()函数把session保存到MySQL数据库实例
- PHP魔术方法__GET、__SET使用实例