Ashok
Ashok

Reputation: 461

Get all static variables of a class without reflection

We have an exception Class A with a few fault codes defined as public static final and it is referenced in many files (more than 100) in our source code. We want all these fault codes in Class B for some processing.

Currently we have implemented a method called getFaultCodes() in Class A to build a list of fault codes and return the same. The problem with this approach is that whenever an fault code is introduced, it has to be added in getFaultCode method as well. This is error prone, as a user may forget to add the new code to the method.

Moving these fault codes under an enum requires changes in many files all over the source code, so we don't want 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;
   }
}

We are thinking about using reflection, but I'm posting in this forum just to check if there is a better solution. Please provide your suggestion to solve this problem.

Upvotes: 4

Views: 1468

Answers (2)

Ashok
Ashok

Reputation: 461

I have modified code code like below:

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;

}

So that I need not to change the variables occurrences "faultCode" in the source code, I can access the list of fault codes from other class.

Upvotes: 0

fge
fge

Reputation: 121810

Maybe you can go through an interface:

public interface FaultCodeProvider
{
    String getFaultCode();
}

Then have your enums implement it:

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;
    }
}

Collecting them from the enum is then as easy as cycling through the enum's values().

Upvotes: 6

Related Questions