共計 853 個字符,預(yù)計需要花費(fèi) 3 分鐘才能閱讀完成。
在 Java 中,可以使用反射機(jī)制來獲取對象的屬性值。下面是一個簡單的示例代碼:
import java.lang.reflect.Field;
public class Main {public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {// 創(chuàng)建一個對象
Person person = new Person("John", 25);
// 獲取屬性值
String name = (String) getValue(person, "name");
int age = (int) getValue(person, "age");
// 輸出屬性值
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
// 獲取對象的屬性值
public static Object getValue(Object object, String fieldName) throws NoSuchFieldException, IllegalAccessException {// 獲取對象的 Class 對象
Class<?> clazz = object.getClass();
// 獲取屬性
Field field = clazz.getDeclaredField(fieldName);
// 設(shè)置屬性可訪問
field.setAccessible(true);
// 獲取屬性值
return field.get(object);
}
}
class Person {private String name;
private int age;
public Person(String name, int age) {this.name = name;
this.age = age;
}
// getters and setters...
}
在上面的示例中,“Person" 類有兩個私有屬性 "name" 和 "age”。通過反射的方式,可以獲取和輸出這兩個屬性的值。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完