Java中反射方法
对连续的成员变量进行批量赋值操作
/**
* 反射set设置属性,将一个对象一个一个进行设置,但是明确对象的set属性结尾一定是i结尾
*
* @param object 传入对象
* @param setStringBase set属性的基础名,如setStudentGrade
* @param list 要设置的数据,会将list里面的一个一个设置进去,list一个数据对应一个对象的属性i
* @return
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
*/
public static Object setMulty(Object object, String setStringBase, List<?> list, int attributeStart) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class<?> aClass = object.getClass();
for (int i = attributeStart; i < list.size(); i++) {
Method method = aClass.getMethod(setStringBase + i, list.get(i).getClass());
method.invoke(object, list.get(i));
}
System.out.println("object = " + object);
return object;
}
实际应用
import com.NAVSupport.common.utils.ouc.ObjectUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private Double studentGreat0;
private Double studentGreat1;
private Double studentGreat2;
public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
Student student = new Student();
List<Double> doubles = new ArrayList<>();
for (int i = 0; i < 3; i++) {
doubles.add((double) i);
}
Object studentGreat = ObjectUtils.setMulty(student, "setStudentGreat", doubles, 0);
System.out.println("studentGreat = " + studentGreat);
}
}