共計 1185 個字符,預(yù)計需要花費 3 分鐘才能閱讀完成。
在 Java 中,可以使用反射來遍歷實體類并獲取屬性值。下面是一個示例代碼:
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Main {public static void main(String[] args) {
// 創(chuàng)建實例對象
Person person = new Person("John", 25, "Male");
// 獲取實例對象的 Class 對象
Class clazz = person.getClass();
// 獲取所有的字段(Field)
Field[] fields = clazz.getDeclaredFields();
// 遍歷字段
for (Field field : fields) {
// 獲取字段名
String fieldName = field.getName();
// 構(gòu)造對應(yīng)的 get 方法名
String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
try {
// 獲取對應(yīng)的 get 方法
Method getMethod = clazz.getMethod(getMethodName);
// 調(diào)用 get 方法獲取屬性值
Object value = getMethod.invoke(person);
// 輸出屬性名和屬性值
System.out.println(fieldName + ":" + value);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {e.printStackTrace();
}
}
}
}
class Person {
private String name;
private int age;
private String gender;
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {return name;}
public int getAge() {return age;}
public String getGender() {return gender;}
}
上述代碼中,通過反射獲取實例對象的 Class 對象,然后使用 getDeclaredFields()
方法獲取所有的字段(Field),再通過構(gòu)造對應(yīng)的 get 方法名,使用反射獲取對應(yīng)的 get 方法,并調(diào)用 get 方法獲取屬性值。最后遍歷輸出屬性名和屬性值。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完