Get all static class variables without reflection

We have a Class A exception with several error codes defined as public static final, and in many files (over 100) we refer to our source code. We want all these DTCs in class B to be processed.

We have currently implemented a class method getFaultCodes()in class A to create a list of fault codes and return them. The problem with this approach is that whenever an error code is entered, it must also be added to the method getFaultCode. This is a mistake because the user may forget to add new code to the method.

Moving these trouble codes under enumrequires changes to many files throughout the source code, so we don’t want to do this.

class ExceptionA  {
   public static final String faultCode1 = "CODE1";
   public static final String faultCode2 = "CODE1";
   public static final String faultCode3 = "CODE1";

   List<String> getFaultCodes(){
         list.add(faultCode1);
         ......
         return list;
   }
}

, , , . , .

+4
2

, :

class ExceptionA  {

   public enum codes {
        CODE1("CODE1"),
        CODE2("CODE2"),
        CODE3("CODE3"),

       private String code;

      codes(String code){
          this.code = code;
      }

      public String getCode() {
          return this.code;
      }  
   }
   public static final String faultCode1 = code.CODE1;
   public static final String faultCode2 = code.CODE2;
   public static final String faultCode3 = code.CODE3;

}

"faultCode" , .

0

, :

public interface FaultCodeProvider
{
    String getFaultCode();
}

:

public enum DefaultFaultCodes
    implements FaultCodeProvider
{
    FAULT1("text for fault 1"),
    // etc
    ;

    private final String value;

    DefaultFaultCodes(final String value)
    {
        this.value = value;
    }

    @Override
    public String getFaultCode()
    {
        return value;
    }
}

, values().

+6

All Articles