java 反射 proper_如何利用反射批量修改java类某一属性的代码详解

下面看下代码,具体代码如下所示:

package utils.copyProperty;

import java.beans.Introspector;

import java.beans.PropertyDescriptor;

import java.lang.reflect.Method;

import java.util.ArrayList;

import java.util.Collection;

public class CopyProperty {

public static PropertyDescriptor[] getPropertyDescriptor(Class> clz) throws Exception {

PropertyDescriptor[] propertyDescriptorsFull =

Introspector.getBeanInfo(clz).getPropertyDescriptors();

PropertyDescriptor[] ps = new PropertyDescriptor[propertyDescriptorsFull.length - 1];

int index = 0;

for (PropertyDescriptor p : propertyDescriptorsFull) {

if (!p.getName().equals("class")) {

ps[index++] = p;

}

}

return ps;

}

public static T setPropertyValue(T t,String propertyName,Object value){

try{

//获取属性描述类

PropertyDescriptor[] pdArr = getPropertyDescriptor(t.getClass());

PropertyDescriptor myPD = null;

for (PropertyDescriptor p : pdArr) {

//类属性与传入属性对比,为了统一都转小写

if(p.getName().toLowerCase().equals(propertyName.toLowerCase())){

//获取需要修改属性

myPD = p;

break;

}

}

//根据需要修改属性,修改属性值

if(myPD!=null){

Method writeMethod = myPD.getWriteMethod();

if(myPD.getPropertyType().getName().equals("java.lang.String"))

{

writeMethod.invoke(t, value.toString());

}else{

writeMethod.invoke(t, value);

}

}

}catch(Exception e){

e.printStackTrace();

}

return t;

}

public static Collection setPropertyValue(Collection coll,String propertyName,Object value) {

if(coll!=null)

for(T t : coll){

setPropertyValue(t,propertyName,value);

}

return coll;

}

public static void main(String args[]) throws Exception{

ArrayList students=new ArrayList();

Student student=new Student();

Student student1=new Student();

students.add(student);

students.add(student1);

for (Student stu:students){

System.out.println("赋值之前:"+stu.getValidStatus());

}//修改validStatus为0

CopyProperty.setPropertyValue(students, "validStatus", "0");

for (Student stu:students){

System.out.println("赋值之后:"+stu.getValidStatus());

}

}

public static class Student{

private String name ;

private String sex;

private String validStatus="1";

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getSex() {

return sex;

}

public void setSex(String sex) {

this.sex = sex;

}

public String getValidStatus() {

return validStatus;

}

public void setValidStatus(String validStatus) {

this.validStatus = validStatus;

}

}

}

把student的validStatus状态都修改为0,测试效果如下:

59400328c75a0cc99a0f6a9b95782314.png

到此这篇关于如何利用反射批量修改java类某一属性的文章就介绍到这了,更多相关批量修改java类某一属性内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值