int y = x.getInt(x);
这实际上是错误的,没有任何意义. Field.getInt的JavaDoc说明如下:
Parameters:
obj – the object to extract the int value from
Returns:
the value of the field converted to type int
字段是为类“全局”定义的.如果要访问该类的某个实例的字段值,则需要将该实例提供给getField(Object)方法.
它甚至更进一步说:
Throws:
IllegalArgumentException – if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof), or if the field value cannot be converted to the type int by a widening conversion.
NullPointerException – if the specified object is null and the field is an instance field.
因此,除非字段是静态字段,否则不能像注释中建议的那样提供null.您也不能使用字段本身(x)作为参数,因为它不是该类的实例.
在特定情况下,当在接口中定义字段时,所有字段将自动变为静态最终字段.因此,您可以提供null作为参数,因为不需要进一步的信息.
但由于Field的这种方法也可以用于其他情况(非静态的),因此需要有这个参数.