어떻게 반 사 를 이용 하여 자바 류 의 특정한 속성 을 대량으로 수정 하 는 코드 를 상세 하 게 설명 합 니까?
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 의 valid Status 상 태 를 0 으로 수정 합 니 다.테스트 효 과 는 다음 과 같 습 니 다.
반 사 를 이용 하여 자바 류 의 특정한 속성 을 대량으로 수정 하 는 방법 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.자바 류 의 특정한 속성 내용 을 대량으로 수정 하 는 것 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 응원 바 랍 니 다!