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

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

    see this example :

    PersonneTest pt=new PersonneTest();
    System.out.println(pt.getClass().getDeclaredFields().length);
    Field[]x=pt.getClass().getDeclaredFields();
    System.out.println(x[1].getName());
    
    0 讨论(0)
  • 2020-11-22 01:34

    You can do like this:

    Field[] fields = YourClass.class.getDeclaredFields();
    //gives no of fields
    System.out.println(fields.length);         
    for (Field field : fields) {
        //gives the names of the fields
        System.out.println(field.getName());   
    }
    
    0 讨论(0)
提交回复
热议问题