Is it possible to get the declaration name of an object at runtime in java?

前端 未结 4 504
遇见更好的自我
遇见更好的自我 2020-12-18 06:18

Lets say i have a a button somewhere in the code: \"JButton closeButton\". I dont know that it\'s called \"closeButton\" but that\'s what i want to find out.

At run

4条回答
  •  醉梦人生
    2020-12-18 06:41

    
    import java.lang.reflect.*;

    public class field1 { private double d; public static final int i = 37; String s = "testing";

      public static void main(String args[])
      {
         try {
            Class cls = Class.forName("field1");
    
            Field fieldlist[] 
              = cls.getDeclaredFields();
            for (int i 
              = 0; i < fieldlist.length; i++) {
               Field fld = fieldlist[i];
               System.out.println("name
                  = " + fld.getName());
               System.out.println("decl class = " +
                           fld.getDeclaringClass());
               System.out.println("type
                  = " + fld.getType());
               int mod = fld.getModifiers();
               System.out.println("modifiers = " +
                          Modifier.toString(mod));
               System.out.println("-----");
            }
          }
          catch (Throwable e) {
             System.err.println(e);
          }
       }
    

    }

    This should give you a list of all the fields of the class.

提交回复
热议问题