Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / October 2006

Tip: Looking for answers? Try searching our database.

Field name from "this"

Thread view: 
G. Ralph Kuntz, MD - 18 Oct 2006 16:38 GMT
I am trying to find a way to get a field's name (variable name) given a
pointer to "this".

I am trying to log all user actions in an application. In every case
where a JButton appears in my app, I use a subclass:

JButton aButton = new MyButton();

I can modify the constructor for MyButton to automatically log when the
button is clicked by adding an ActionListener.  I would like to print
the class of the containing window (JDialog or JFrame) and the variable
name of the button.  This way I can recreate what the user clicked.

I realize that I could use getClass().getFields() and loop thought the
Field[] until I find "this" then use Field.getName(), but I was hoping
for a faster way (less impact on performance).

Any ideas?
Thomas Weidenfeller - 18 Oct 2006 16:57 GMT
> I am trying to find a way to get a field's name (variable name) given a
> pointer to "this".

Such attempts are usually an indication of a misguided design. Rethink
your design.

/Thomas
Signature

The comp.lang.java.gui FAQ:
http://gd.tuwien.ac.at/faqs/faqs-hierarchy/comp/comp.lang.java.gui/
ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq

G. Ralph Kuntz, MD - 18 Oct 2006 17:57 GMT
This does not answer my question.  I have about 200000 lines of code
and cannot "rethink my design". I am trying to solve a real-world
problem with customers saying they did/did not do something and I need
to find out what they really did.  I need to find a solution to my
original question or instrument 500+ JButtons with JComponent.setName()
calls.

On Oct 18, 11:57 am, Thomas Weidenfeller <nob...@ericsson.invalid>
wrote:

> > I am trying to find a way to get a field's name (variable name) given a
> > pointer to "this".Such attempts are usually an indication of a misguided design. Rethink
[quoted text clipped - 3 lines]
> --
> The comp.lang.java.gui FAQ:http://gd.tuwien.ac.at/faqs/faqs-hierarchy/comp/comp.lang.java.gui/ftp://ftp.cs.
uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq
Robert Klemme - 18 Oct 2006 20:35 GMT
> This does not answer my question.  I have about 200000 lines of code
> and cannot "rethink my design". I am trying to solve a real-world
> problem with customers saying they did/did not do something and I need
> to find out what they really did.  I need to find a solution to my
> original question or instrument 500+ JButtons with JComponent.setName()
> calls.

This sounds like a use case for tracing since you do that for debugging
purposes only.  Did you consider using the JVM Tool Interface?  The JVM
offers quite a lot of ways to instrument code and generally examine the
running process.

http://java.sun.com/j2se/1.5.0/docs/guide/jvmti/jvmti.html

Kind regards

    robert
Thomas Hawtin - 18 Oct 2006 17:25 GMT
> I am trying to find a way to get a field's name (variable name) given a
> pointer to "this".
[quoted text clipped - 12 lines]
> Field[] until I find "this" then use Field.getName(), but I was hoping
> for a faster way (less impact on performance).

Is such a loop going to take significantly long compared with the rest
of the action?

If you are sufficiently twisted, from within the constructor of MyButton
you can get the stack trace. Later, at button click time, the stack
trace can be used to find the source of the code that created the
button. Cameron Purdy presented a similar icky piece of code in his weblog:

http://www.jroller.com/page/cpurdy?entry=yaul_trac

Tom Hawtin
IchBin - 18 Oct 2006 19:19 GMT
> I am trying to find a way to get a field's name (variable name) given a
> pointer to "this".
[quoted text clipped - 14 lines]
>
> Any ideas?

The only thing I can think of is to create a class that initializes,
manages, searches an array to print\return the particular JDialog or
JFrame info. Just make sure you do a binary search. You could hard code
or dynamically build this array at initialization of that class. It
could be loaded and initialized before you build your GUI interfaces
(hard coded) or after by dynamically building it. That is, the targeted
array for doing the binary search.

When hard coding the setName() should be a number for an index so you
can do a binary search of the array by just converting the getname() to
an integer for the binary search.. What array, structure, collection,
vector.. is up to your own discretion. You can google for this code or
look at the API's.

This is a general description. At least this entire process can all be
encapsulated into it own class and the he performance will be O(log N).
I think I would approach it this way.

Signature

Thanks in Advance...                      http://ichbin.9999mb.com
IchBin, Pocono Lake, Pa, USA              http://weconsultants.phpnet.us
__________________________________________________________________________

'If there is one, Knowledge is the "Fountain of Youth"'
-William E. Taylor,  Regular Guy (1952-)

Chris Uppal - 18 Oct 2006 19:42 GMT
> I realize that I could use getClass().getFields() and loop thought the
> Field[] until I find "this" then use Field.getName(), but I was hoping
> for a faster way (less impact on performance).

Given the nature of your (rather unusual, but understandable) requirements, I
would do just that.  The performance hit will be totally neglible -- but even
if it wasn't, it wouldn't be /you/ who suffered.

   -- chris
Seamus - 18 Oct 2006 19:46 GMT
> I am trying to find a way to get a field's name (variable name) given a
> pointer to "this".
[quoted text clipped - 14 lines]
>
> Any ideas?
A Listener ?
Piotr Kobzda - 18 Oct 2006 21:47 GMT
> Any ideas?

import java.awt.event.*;
import javax.swing.JButton;

import org.aspectj.lang.Signature;

public aspect ButtonsLogging {

    after(JButton button) :
        set(JButton+ *.*) && args(button)
    {
        final Signature sig = thisJoinPointStaticPart.getSignature();
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("pressed "
                        + sig.getDeclaringType() + "." + sig.getName());
            }
        });
    }
}

piotr
Brandon McCombs - 18 Oct 2006 23:29 GMT
> I am trying to find a way to get a field's name (variable name) given a
> pointer to "this".
[quoted text clipped - 14 lines]
>
> Any ideas?

I did this when using textfields to know which textfield currently had
focus which would dictate which attribute from an object class to
modify.  I made a custom textfield class that implemented FocusListener.
Each time focusGained() was called it set the value of a global variable
which contained the name of the field that I set during the field's
instantiating using setName(). This has worked for me for dialogs where
the # of textfields was unknown and could vary from 1 to 50 or more.

I also had a document listener for the textfields so that when a change
was detected in the fields' text I'd grab the value of my global
variable to determine which field was modified and the text in the field
was the new value for the attribute that corresponded to that field. I
found the attribute in a vector by searching for its name(from the
global variable) and assigned it the new value. Later I saved all the
attribute data back to the LDAP server.

There are probably better ways but that's just an idea that may work for
you in a bind.
Mark Rafn - 19 Oct 2006 00:58 GMT
>I am trying to find a way to get a field's name (variable name) given a
>pointer to "this".

You can't reliably do that. A given object could be pointed to by multiple or
no fields.  You're better off taking a stack trace at instantiation, and
logging the class and linenum that created you.  This works even when you're
an anonymous subclass or a local variable.

>I am trying to log all user actions in an application. In every case
>where a JButton appears in my app, I use a subclass:
[quoted text clipped - 3 lines]
>the class of the containing window (JDialog or JFrame) and the variable
>name of the button.  This way I can recreate what the user clicked.

Don't all your buttons have labels anyway?  How do users know what they do
otherwise?  Or at least they have actions.  you can log the action class name.

>I realize that I could use getClass().getFields() and loop thought the
>Field[] until I find "this" then use Field.getName(), but I was hoping
>for a faster way (less impact on performance).

You're only doing this in debug mode, at instantiation time, right?  How much
performance impact do you think this is going to have?
--
Mark Rafn    dagon@dagon.net    <http://www.dagon.net/>
Larry Barowski - 19 Oct 2006 15:41 GMT
>I am trying to find a way to get a field's name (variable name) given a
> pointer to "this".
[quoted text clipped - 12 lines]
> Field[] until I find "this" then use Field.getName(), but I was hoping
> for a faster way (less impact on performance).

Your buttons are all assigned to fields? That seems very unusual,
unless you are using a gui builder of some sort.

Is the button text, parent type, and dialog or frame title enough
information to identify the button? If you don't have a lot of tabs
or card layouts with repeated button names in them, it should be.
Otherwise, you could name every button parent in the app using
setName() (assuming names are not used for something else),
then identify buttons by button text and parent name.

Also, you can just use  Toolkit.addAWTEventListener()  to catch
all the button clicks, instead of subclassing JButton.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.