You can access a method using Class.getMethod
, which returns a Method
object. You then invoke that Method
object by passing it the instance and arguments:
method.invoke(result.get(Name), whateverArguments);
Your question was a bit ambiguous as to whether you're really accessing a field. If that's the case, you can get a Field
via Class.getField
, and get its value via the get
method, again passing in the instance on which you want to get the field.
In either case, the result is typed as Object
, and you need to downcast that to the expected type. In the case of a primitive like int
, the object returned will be a boxed type like Integer
, which you can auto-unbox to int
:
int foo = (Integer) method.invoke(...);
The whole thing would look something like:
Field field = I2CRegisterValues.getField(fieldName);
Object o = field.get(result.get(Name));
int fieldValue = (Integer) o;
... where fieldName
is a String
variable in a loop of your String[] names
. You can also do the above as a one-liner:
int fieldValue = (Integer) I2CRegisterValues
.getField(fieldName)
.get(result.get(Name));