Java: Can I use a constant string as an enum key value? -


this question has answer here:

i have enum class several key. number of keys should have same string value. sonar yells @ me replace same string values constant value.

for example:

public enum message_types {  key1("val1"), key2("val2"), key3("val3"), key4("val2"), key5("val4"), key6("val2"), //etc.  } 

so, sonar wants me :

define constant instead of duplicating literal...

for "val2" since defined 3 or more times. how can achieve that?

auto extracting value constant puts right after enum keys, value of enum key doesn't recognize of course. so, tried put on top of enum class

public enum message_types {      private static final string val2 = "val2";      key1("val1"),     key2(val2), ... } 

and "syntax error" errors on line.

please advise.

thanks!

you cannot declare static fields in enum class before declaring enum values.
, declaring static fields after enum values not allow use them in enum constructor.
extract string values in class , reference them in enum values declaration.

for example :

public final class mymessageconstant{      public static final string val1 = "val2";     public static final string val2 = "val2";      private mymessageconstant(){     } } 

and enum :

public enum message_types {      key1(mymessageconstant.val1),     key2(mymessageconstant.val2), ... } 

if makes sense keep string values private enum class, can declare constant class private static final class member of enum :

public enum types {      key1(mymessageconstant.val1), key2(mymessageconstant.val2),...     key4(mymessageconstant.val2),      private static final class mymessageconstant {                private static final string val1 = "val2";        private static final string val2 = "val2";                private mymessageconstant() {}     }      private string value;      private types(string value) {       this.value = value;     }  } 

Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -