How to get the value of an enumeration present in an inner class via Reflection

Hi everyone, I'm trying to access the enum value present in the inner class as shown below, but what I get is not the value, but the key. The need of my application is that I need to access this value using reflection.

public class Test{
 static class TwelveByTwentyFour {
     public static enum BET_TYPE_NAME {
         Direct12(12),AllOdd(12),AllEven(12), First12(12), Last12(12);

    private int value;
    BET_TYPE_NAME(int value){
                this.value = value;
            }

            public  int getValue() {
                return value;
            }
            public void setValue(int value) {
                this.value = value;
            }
    }

 }
 public static String getBetTypeLength(String gameName,String betType) throws ClassNotFoundException, IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException{
        return Class.forName(Test.class.getCanonicalName()+"$"+gameName+"$"+"BET_TYPE_NAME").getDeclaredField(betType).get(null).toString();
    }
 public static void main(String[] args) throws IllegalArgumentException, SecurityException, ClassNotFoundException, IllegalAccessException, NoSuchFieldException {
    System.out.println(getBetTypeLength("TwelveByTwentyFour", "AllEven"));
}

}

In doing so, I get "AllEven"as output instead "12". Can someone please help me by telling me how I can get the value.

+4
source share
1 answer

BET_TYPE_NAME.AllEven.toString(), Enum , BET_TYPE_NAME.AllEven.name(), "AllEven".

"12", toString() BET_TYPE_NAME, :

@Override
public String toString() {
    return this.value;
}

Field.get(null) BET_TYPE_NAME getValue() :

return Integer.toString(((TwelveByTwentyFour.BET_TYPE_NAME)
        Class.forName(Test.class.getCanonicalName()+"$"+gameName+"$"+"BET_TYPE_NAME")
                .getDeclaredField(betType).get(null)).getValue());

, , value final — .

+1

Source: https://habr.com/ru/post/1648729/


All Articles