Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Class Field / Method getInt [closed]

Tags:

java

I have an interface which contains only int values (so in essence, it is pretty similar to an enum).

I want to iterate the interface values, using the following piece of code:

for (Field x : MyInterface.class.getDeclaredFields())
{
    int y = x.getInt(x);
    // do something with 'y'...
}

The way I see it, either the getInt method can be static, or it doesn't need any arguments.

So why does this method need both 'this' and the additional argument?

Is there any plausible scenario for them to be different?

like image 797
barak manos Avatar asked Nov 01 '22 07:11

barak manos


1 Answers

int y = x.getInt(x);

This is actually wrong and doesn't make any sense. The JavaDoc of Field.getInt says the following:

Parameters: obj - the object to extract the int value from

Returns: the value of the field converted to type int

A Field is "globally" defined for a class. If you want to access a value of a field of a certain instance of that class, then you need to supply that instance to the getField(Object) method.

It even goes further and says:

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.

So you cannot provide null as it was suggested in the comments, unless the field is a static field. You can also not use the field itself (x) as the parameter, since it is not an instance of that class.

In your specific case, when a field is defined within an interface, all fields become static final automatically. Thus you can provide null as the parameter, because there is no further information needed.

But since this method of Field can also be used in other cases (non-static ones), there needs to be this parameter.

like image 56
noone Avatar answered Nov 15 '22 03:11

noone