Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

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

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 runtime, that button gets clicked and once it does i can find out a lot about it through reflection and the AWT api - BUT what i can't do is find out where it is - how it's called in the code, what name is it declared as ("closeButton").

Is it possible to find this out from the JVM?

Is there a way to compile and run the code in such a way that the names for the instances get preserved at runtime?

Is there perhaps some type of 'javaagent' out there (free if possible) that can help me out in this situation?

Thanks

EDIT (14:23 EDT):

I am using a button as an example but it could be any type of component that can hold a value and have ActionListeners attached to it. I can obtain every bit of information via reflection about that component but i cant find it in the code. Even if there are 10 components that have been declared with the same name, that still gives me a lead, i can eliminate possibilities.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)


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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...