Can I print out the name of the variable?

后端 未结 6 642
独厮守ぢ
独厮守ぢ 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:46

    There are some 'special case' that u can have workaround for this (which is told by other), but the most important question is: why would you want to do this (printing out variable name)?

    From my experience, 99.9% of similar questions (how to print variable name? how to get variable depends on user inputting variable name? etc) is in fact raised by beginner of programming and they simply have made incorrect assumptions and designs. The goal they are trying to achieve normally can be done by more appropriate design.


    Edit

    Honestly I still do not think what you are trying to do is the way to go, but at least I think the following is a workable answer:

    It is more or less a combination of previous answer:

    (Haven't try to compile but at least it give u an idea)

    class Constants {
      public static final int FOO = 123;
      public static final int BAR = 456;
    
      private static Map constantNames = null;
    
    
      public static String getConstantName(int constVal) {
        if (constantNames == null) {
          Map cNames = new HashMap()
          for (Field field : MyClass.class.getDeclaredFields()){
            if ((field.getModifiers() & (Modifier.FINAL | Modifier.STATIC)) != 0) {
                && int.class == field.getType()){
              // only record final static int fields
              cNames.put((Integer)field.get(null), field.getName());
            }
          }
          constNames = cNames;
        }
        return constantNames.get(constVal);
      }
    }
    

    assuming you want to get a constant name, just do:

    Constants.getConstantName(123);  // return "FOO"
    

提交回复
热议问题