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

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

    import java.lang.reflect.Field;
    
    
    public class test {
    
     public int i = 5;
    
     public Integer test = 5;
    
     public String omghi = "der";
    
     public static String testStatic = "THIS IS STATIC";
    
     public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
      test t = new test();
      for(Field f : t.getClass().getFields()) {
       System.out.println(f.getGenericType() +" "+f.getName() + " = " + f.get(t));
      }
     }
    
    }
    

提交回复
热议问题