How do I initialize an input field without writing an IF statement?

I have a similar enumeration

public enum Field {
     A,B,C,D,E ....;

     private Field(){
     }
}

I have a class panel, which initializes fields with the field array:

public class Panel {
     Text@R_976_2419@ A; 
     Text@R_976_2419@ B;
     Text@R_976_2419@ C;
     Text@R_976_2419@ D;
     Text@R_976_2419@ E;
     ...


     public Panel(Field[] fields){
          this.fields = fields;
          init();
     }

     public void initA(){}
     public void initB(){}
     public void initC(){}
     public void initD(){}
     public void initE(){}
}

My question is, how do I initialize a given field without writing an IF statement?

I can't find any solution. I'm initializing now, as shown below:

public void init(){
      for(int i = 0 ; i < fields.length; i++){
          if(fields[i] == Field.A){
              initA();
          } else if(fields[i] == Field.B){
              initB();
          } else if(fields[i] == Field.C){
              initC();
          } else if(fields[i] == Field.D){
              initD();
          } else if(fields[i] == Field.E){
              initE();
          }  ....
      }
}

Solution

It sounds like your design may need attention some suggestions:

>Add the init method to the enumeration So then you can traverse the array, your enumeration and call init's method on it, so the enumeration knows how to do its own initialization > create a command object initialization and create your enumeration map as the key and command as the value Cycle around the map running command for each enumeration. > Using reflection – cost wise, I won't worry too much about this unless your system is after very low latency

For the first bullet, you can change the Text@R_976_2419 @To preserve the field type, for example

Text@R_976_2419@ A = new Text@R_976_2419@(Field.A);
Text@R_976_2419@ B = new Text@R_976_2419@(Field.B);

Therefore, if Text@R_976_2419 @If you know it's a, e, then you just need to loop your field []. When it finds its thing, Text@R_976_2419 @Run init code (which can be stored for specific enumeration instances) Of course, you need to register all data in the data structure somewhere Text@R_976_2419 @Instance, because you seem very opposed to using the very widely used reflection API

Essentially, field and Text@R_976_2419 @There must be a link between Without your statement, Java can't read your ideas Well, at least until Google launches their telepathic API (this may only apply to go...) This can be done based on naming (reflection), hard coded logic (IFS or switches), or state For the latter, this means combining field with Text@R_976_2419 @As I demonstrated in the constructor example above

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>