简体   繁体   中英

Is there a way to identify the object calling a specific method in java?

I need to be able identify the Object which is calling a specific method. So if for example I have the following

    JLabel l = new JLabel("Hello");
    JLabel label = new JLabel("HELLO");
    label.setText("BYE");

I need to be able to identify the object in variable label is actually calling setText and not l. I did manage to get the type of the object calling the method, in this case being JLabel, as I am using SOOT to be able to get method information. However what I actually need is the object making use of this method.

Is there a way to be able to identify the actual object calling the method?

Yes, you could find who is calling via reflection. See this stack overflow post: How do I find the caller of a method using stacktrace or reflection? for more info on how to do that.

However, I would be concerned that you're trying to do something in a much harder way than necessary to achieve whatever end goal you are after. Could you pass "this" in as a parameter to the sub-methods that need to know who's calling?

There is no method that is appropriate. You should pass a parameter to your method to tell it what to do, no go sniffing up the stack.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM