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

后端 未结 8 2371
一生所求
一生所求 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

    All you need to do is make an array of fields and then set it to the class you want like shown below.

    Field fld[] = (class name).class.getDeclaredFields();   
    for(Field x : fld)
    {System.out.println(x);}
    

    For example if you did

    Field fld[] = Integer.class.getDeclaredFields();
              for(Field x : fld)
              {System.out.println(x);}
    

    you would get

    public static final int java.lang.Integer.MIN_VALUE
    public static final int java.lang.Integer.MAX_VALUE
    public static final java.lang.Class java.lang.Integer.TYPE
    static final char[] java.lang.Integer.digits
    static final char[] java.lang.Integer.DigitTens
    static final char[] java.lang.Integer.DigitOnes
    static final int[] java.lang.Integer.sizeTable
    private static java.lang.String java.lang.Integer.integerCacheHighPropValue
    private final int java.lang.Integer.value
    public static final int java.lang.Integer.SIZE
    private static final long java.lang.Integer.serialVersionUID
    

提交回复
热议问题