Can I print out the name of the variable?

后端 未结 6 646
独厮守ぢ
独厮守ぢ 2021-01-12 15:26

I have created a no. of constant variables, more than 1000, those constants are unique integer.

public static final FOO  335343
public static final BAR  2342         


        
6条回答
  •  臣服心动
    2021-01-12 15:50

    You can use something like:

    for (Field field : MyClass.class.getDeclaredFields()){
        if (field.getType().toString().equals("int")){
            int val = (Integer)field.get(MyClass.this);
            switch (val){
                case 335343:
                case 234234:
                    System.out.println(field.getName());
            }
        }
    }
    

    Remember to change MyClass for your class name and that at least one instance should exist to get the value of the field. So, if you are planning on testing the code in a main method, you should change MyClass.this to something like new Myclass(). Another thing to remember is that the fields are attributes and not method variables (so it won't work if you are using this to access variables declared inside a method).

提交回复
热议问题