Java Reflection: How to get the name of a variable?

后端 未结 8 2381
一生所求
一生所求 2020-11-22 00:28

Using Java Reflection, is it possible to get the name of a local variable? For example, if I have this:

Foo b = new Foo();
Foo a = new Foo();
Foo r = new Fo         


        
8条回答
  •  花落未央
    2020-11-22 01:10

    update @Marcel Jackwerth's answer for general.

    and only working with class attribute, not working with method variable.

        /**
         * get variable name as string
         * only work with class attributes
         * not work with method variable
         *
         * @param headClass variable name space
         * @param vars      object variable
         * @throws IllegalAccessException
         */
        public static void printFieldNames(Object headClass, Object... vars) throws IllegalAccessException {
            List fooList = Arrays.asList(vars);
            for (Field field : headClass.getClass().getFields()) {
                if (fooList.contains(field.get(headClass))) {
                    System.out.println(field.getGenericType() + " " + field.getName() + " = " + field.get(headClass));
                }
            }
        }
    
        

    提交回复
    热议问题