You appear to want to pass the name of a parameter into a method and then
do something with that parameter. You seem to be intent on not providing any context of your problem, which leads me to believe you are merely interested in the possibility, and are not looking to use this in actual application code. As such, I will show you for the sake of reference:
public void method(String parameterName) {
try {
// We can get the current field value:
int value = (int) getClass().getField(parameterName).get(this);
// And update it (for example, set it to 23)
getClass().getField(parameterName).set(this, 23);
catch (NoSuchFieldException | IllegalAccessException ex) {
// Field does not exist or is not public.
}
}
It can be used as follows (this sets the value of field a
to 23 if it exists).
MyClass instance = new MyClass();
instance.method("a");
Note that this requires the field to be public. It is possible to this with non-public fields as well but that is an even worse idea, since it bypasses the entire access control mechanism of Java. There are better solutions which involve using a Map
object to implement a similar kind of structure. These are definitely better than using this.
Last remark (I cannot stress this enough): Do not use Reflection calls in actual code! It is always possible to do everything you need to without it (For example, use a Map<String, Integer>
instead of individual fields).