0

I am working on Android Studio, and I want to accomplish the following:

I have this class with some variables:

class test {
   private String prop1;
   private int prop2;
   private boolean prop3;
}

I want to create a 'generic' method which can change some variable to a new value, like:

public changeVar(Variable var, Value val) {
    this.var = val;
}

I was wondering if there is any clever way of doing that without the need to make tens of set methods for each variable.

Thank you.

hiddeneyes02
  • 2,562
  • 1
  • 31
  • 58

1 Answers1

0

If you are just tired to write (or generate) getters/setter for your code and/or do not like to have that getter/setter stuff boilerplating your code then I would recommend to check some external tool like Lombok, see especially annotations @Getter&@Setter. For Android Studio.

See also Is it safe to use Project Lombok?

If you really want to make it as you suggest then the answer might be reflection. There are some posts about it in SO, like:

Java, set field value with reflection

java reflection nested object set private field

But: I am not too so sure if it is clever to do it using reflection. It could obfuscate things a lot.

pirho
  • 11,565
  • 12
  • 43
  • 70