Java通过PropertyDescriptor反射调用set和get方法
作者:周XXXX 发布时间:2023-10-11 19:34:17
标签:Java,PropertyDescriptor,反射
本文实例为大家分享了PropertyDescriptor反射调用set和get方法,供大家参考,具体内容如下
第一段:
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;//返回值
}
}
第二段:
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;
}
第三段:
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);
}
}
}
0
投稿
猜你喜欢
- 1. 源码阅读环境搭建ide:IntelliJ IDEA 2020.1包管理:gradleeureka版本:1.10.11Spring Cl
- File类概述File类能新建、删除、重命名文件和目录,但不能访问文件内容本身,如果需要访问文件内容本身,则需要使用后续的输入/输出流。要在
- 前言之前我们提到了 CustomPaint er 的 Paint 可以使用渐变(GradientShader)来填充绘制的图形,本篇我们来介
- 仅供学习交流,禁止商业用途。如侵害利益,联系必删!前言最近一位小伙伴钟爱二次元文化,于是找到半次元这个app,但是很快他就遇到了问题。一、案
- 本文实例讲述了Java Web项目部署在Tomcat运行出错与解决方法。分享给大家供大家参考,具体如下:1、在部署Java Web项目的过程
- 一、interrupt的使用特点我们先看2个线程打断的示例首先是可打断的情况:@Testpublic void interruptedTes
- ViewDragHelper是support.v4下提供的用于处理拖拽滑动的辅助类,查看Android的DrawerLayout源码,可以发
- synchronized都问啥?如果Java面试有什么是必问的,synchronized必定占据一席之地。初出茅庐时synchronized
- 本文为大家分享一个非常简单但又很常用的控件,跑马灯状态的TextView。当要显示的文本长度太长,又不想换行时用它来显示文本,一来可以完全的
- 这几天做项目,有些地方的图片需要用到圆形图片,所以百度了一下,在github上找到一个开源项目,处理很简单,效果如下:使用起来特别简单,一共
- 引出泛型我们通过如下的示例,引出为什么泛型的概念。public class Test {public static void main(St
- Android ListView的Item点击效果的定制
- 微服务治理Spring Cloud 工具套件为微服务治理提供了全面的技术支持。这些治理工具主要包括服务的注册与发现、负载均衡管理、动态路由、
- 注意是maven的webapp:选择maven下一步下一步。maven下载过慢在setting中加入镜像。 我也有疑问这是什么鬼格式,但是证
- 树的结构说得差不多了,现在我们来说说一种数据结构叫做哈希表(hash table),哈希表有是干什么用的呢?我们知道树的操作的时间复杂度通常
- 本文主要记录JAVA中对象的初始化过程,包括实例变量的初始化和类变量的初始化以及final关键字对初始化的影响。另外,还讨论了由于继承原因,
- 上帝之火本系列讲述的是开源实时监控告警解决方案Prometheus,这个单词很牛逼。每次我都能联想到带来上帝之火的希腊之神,普罗米修斯。而这
- 本文实例为大家分享了Java实现简单邮件发送的具体代码,供大家参考,具体内容如下需要的jar包:activation-1.1.1.jarma
- JdbcTypeInterceptor运行时自动添加 jdbcType 属性 * 签名@Intercepts({
- 初学C++的朋友经常在类中看到public,protected,private以及它们在继承中表示的一些访问范围,很容易搞糊涂。今天本文就来