[英]Java Reflection - Accessing Fields of a Field
假設我有課
class car
{
int color = 1;
seats carSeats = new seats();
class seats
{
int numSeats = 4;
}
}
使用 Java 反射,我可以使用以下內容:
car c = new car();
Field[] carFields = c.getClass().getDeclaredFields();
carFields 將 { color, carSeats } 作為字段。 實例 carSeats 有另一個名為 numSeats 的字段。
從技術上講,我應該能夠執行另一個 getFields() 操作,以便:
Field[] seatFields = carFields[1].getClass().getDeclaredFields();
但是我得到了垃圾數據(已聲明,公開?)為什么會這樣? Java 反射對內部類不起作用嗎?
carFields[1].getClass()
將代表一個Field
對象。 你想要carFields[1].getType().getDeclaredFields()
。
另外,正如 BalusC 評論的那樣,要小心。 這些字段不一定按您期望的順序排列。
這是一個簡短的片段,可以為反射提供一些提示
import java.lang.reflect.Field;
公共類汽車{
int color = 1;
int wheels = 4;
Seats carSeats = new Seats();
class Seats {
int numSeats = 4;
}
public static void printFields(Field[] fields, Object o) {
System.out.println(o.getClass());
try {
for (int i = 0; i < fields.length; i++) {
Field f = fields[i];
f.setAccessible(true);
System.out.println(f.getName() + " " +
f.getType().getName() + " " +
f.get(o));
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
Car car = new Car();
Class<?>[] classes = Car.class.getDeclaredClasses();
printFields(Car.class.getDeclaredFields(), car);
for (int i = 0; i < classes.length; i++) {
Class<?> klass = classes[i];
printFields(klass.getDeclaredFields(), car.carSeats);
}
}
}
我發現使用使用反射的編寫代碼很有趣,但真的很難解決問題......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.