如何利用反射批量修改java类某一属性的代码详解
程序员文章站
2022-04-01 18:54:14
下面看下代码,具体代码如下所示:package utils.copyproperty; import java.beans.introspector;import java.beans.propert...
下面看下代码,具体代码如下所示:
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> 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 <t>collection<t> setpropertyvalue(collection<t> 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<student> 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,测试效果如下:
到此这篇关于如何利用反射批量修改java类某一属性的文章就介绍到这了,更多相关批量修改java类某一属性内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!