Java 反射累加集合字段并格式化输出
可以使用反射获取集合中的字段值,然后累加起来,最后格式化输出。
示例代码如下:
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Person> persons = new ArrayList<>();
persons.add(new Person('Alice', 20));
persons.add(new Person('Bob', 30));
persons.add(new Person('Charlie', 40));
int ageSum = 0;
for (Person p : persons) {
try {
Field ageField = Person.class.getDeclaredField('age');
ageField.setAccessible(true);
int age = (int) ageField.get(p);
ageSum += age;
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
System.out.printf('Total age: %d', ageSum);
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
在上面的代码中,我们定义了一个 Person 类,其中包含了 name 和 age 两个字段。然后我们创建了一个 List<Person> 类型的集合,并添加了三个 Person 对象。
接着我们使用反射获取到 Person 类中的 age 字段,然后在循环遍历集合时累加起来。最后使用 printf 方法格式化输出累加结果。
输出结果为:
Total age: 90
原文地址: https://www.cveoy.top/t/topic/lrz7 著作权归作者所有。请勿转载和采集!