Reputation: 75
I need to pass a class variable to an enum while initializing it .But the class variable is not accessible while initializing the enum . So how can this be achieved ?
I tried passing variable of another class, same class where the enum resides . Both didn't work.
public class ComponentConstants {
public Constants constants = Constants.getInstance();
enum FIELDS_RESOURCES {
//instead of text i want to use constants.data_type.text. But I was not able to.
SourcetType(true, "text", "Source Type", "source_type", 255, false); //No I18N
private VOCFIELDS_RESOURCES(boolean isCustomField, String data_type, String field_label, String api_name, int length, boolean isVisible) {
this.isCustomField = isCustomField;
this.data_type = data_type;
this.field_label = field_label;
this.api_name = api_name;
this.length = length;
this.isVisible = isVisible;
}
}
}
In the above I want to use the value from constants since if there is any change there ,it should be reflected in my code too . Single point of constants , but i was not able to use it. How can this be achieved and why is it not allowing to use other variables? Thanks!
Upvotes: 1
Views: 135
Reputation: 14688
public class Main {
public enum Enumeration {
Test(Constants.a, Constants.b); // can refer to constant "a" & "b" static variables
private final String a;
private final String b;
Enumeration(String a, String b) {
this.a = a;
this.b = b;
}
}
public static class Constants {
static String a = "a";
static String b = "b";
}
}
If you utilize static
fields as constants, they can be referenced within enumeration constructors. More details here regarding enum fields.
Upvotes: 1