[英]Java Reflection - Accessing Fields of a Field
Suppose I have the class假设我有课
class car
{
int color = 1;
seats carSeats = new seats();
class seats
{
int numSeats = 4;
}
}
Using Java reflection, I can use the following:使用 Java 反射,我可以使用以下内容:
car c = new car();
Field[] carFields = c.getClass().getDeclaredFields();
carFields would have { color, carSeats } as the fields. carFields 将 { color, carSeats } 作为字段。 The instance, carSeats, has another field called numSeats.
实例 carSeats 有另一个名为 numSeats 的字段。
Technically, I should be able to do another getFields() operation such that:从技术上讲,我应该能够执行另一个 getFields() 操作,以便:
Field[] seatFields = carFields[1].getClass().getDeclaredFields();
But I am given garbage data (DECLARED, PUBLIC?) Why so?但是我得到了垃圾数据(已声明,公开?)为什么会这样? Does Java reflection not work for inner classes?
Java 反射对内部类不起作用吗?
carFields[1].getClass()
is going to represent a Field
object. carFields[1].getClass()
将代表一个Field
对象。 You want carFields[1].getType().getDeclaredFields()
.你想要
carFields[1].getType().getDeclaredFields()
。
Also, as BalusC commented, be careful.另外,正如 BalusC 评论的那样,要小心。 The fields aren't necessarily in the order you expect.
这些字段不一定按您期望的顺序排列。
Here is a short snippet that can give some hints on Reflection这是一个简短的片段,可以为反射提供一些提示
import java.lang.reflect.Field;
public class Car {公共类汽车{
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);
}
}
} }
I find it good fun to use write code that uses reflection, but really hard to trouble shoot...我发现使用使用反射的编写代码很有趣,但真的很难解决问题......
You could use Traverser class of java-util library which traverse every field of a class with the support of nested fields, which is what you want.您可以使用java-util库的Traverser类,它在嵌套字段的支持下遍历类的每个字段,这正是您想要的。
Traverser - Pass any Java object to this Utility class, it will call your passed in anonymous method for each object it encounters while traversing the complete graph.
Traverser - 将任何 Java 对象传递给此 Utility 类,它将在遍历完整图形时为遇到的每个对象调用传入的匿名方法。 It handles cycles within the graph.
它处理图中的循环。 Permits you to perform generalized actions on all objects within an object graph.
允许您对对象图中的所有对象执行通用操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.