简体   繁体   中英

Passing field name as an argument to a method in the same class in Java

public class ConstructorA {
  private String FieldA, FieldB, FieldC;
  public String Setter(String ArgAA, String ArgAB) {
      this.ArgAA = ArgAB;  //or ArgAA could include "this."
  }
  public String Getter(String ArgBA) {
      return ArgBA;
  }
ObjectA = new ConstructorA();
ObjectA.Setter(FieldA, "TextA");
ObjectA.Setter(FieldB, "TextB");
ObjectA.Setter(FieldC, "TextC");
System.out.printf("%s %s %s", ObjectA.Getter(FieldA), ObjectA.Getter(FieldB), ObjectA.Getter(FieldC));

I'm trying to create generic setter and getter (mutator and accessor) methods that would be able to assign and retrieve values to and from fields without a specific pair of such methods for each individual field, by passing the name of the field as an argument into the method pair. This is partly due to curiosity, but also to reduce boilerplate code for cases where objects have a lot of fields, each with its own getter/setter. The code I'm making has been abstracted in the above snippet to show what exactly I wish to accomplish. If any extra detail or clarification is needed or anything seems ambiguous, please don't hesitate to ask.

I understand the code above is rather ridiculous and likely resembles pseudocode more than java, since the above would not work at all, I think. But is anything remotely similar to the above possible? I'm new to Java and so not very familiar with its features and limitations. I understand something similar would be possible in C, using pointers?

Anyhow, sorry for the lengthy text, and thanks in advance! Any input is valuable and much appreciated.

Don't do this.

If a class has many getters, it is badly designed.

You are essentially treating an object as a Map of names to values. Perhaps your use case is actually that you need a Map from names to values?

I also agree with @Raedwald that too many fields can suggest a possibly design deficiency. That said, there are easier alternatives to reducing code rather than accessing fields via reflection as your post suggests.

One alternative is to add a library like Lombok , which inject code during compile time if special annotations are applied to fields, classes, methods, etc.

For example the @lombok.Data annotation will create getters, setters, toString, constructors, hashcode and equals automatically for you. eg

@lombok.Data
public class LargePojo {
    private String a;
    private int b;
    private List<String> c;
}

You can then access the field a like this:

largePojo.getA()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM