To get the hashCode () of an object that calls a specific method in Java

I am trying to get the hashCode () value for an object calling a specific method in Java. For example,

public class Caller {
    public void aMethod() {
        Callee calleeObj = new Callee();
        calleeObj.aSpecificMethod();
        //do something
    }
}

      

I want to know the value of Caller hashCode () that is called calleeObj.aSpecificMethod()

at runtime. It is designed for plotting object diagram as shown below.

enter image description here

As a limitation, I can only modify .class files using bytecode instrumentation methods.

To do this, I tried the Javassist

tool library inside Callee.aSpecificMethod()

, but this way cannot get the caller object. The reason seems obvious, because the instrumented code on ' Callee.aSpecificMethod()

' can only access the class codes Callee

, not Caller

.

Is there a way to capture the hashCode () value of the receiver object using Javassist? I am also considering ASM 5.0, but using ASM 5.0 is the last option because I have created a lot of Javassist based code so far.

+3


source to share


2 answers


As others say, the method of the method being called cannot access the caller's object, but so far no one has pointed out to you why this would never be possible:

The big misconception about your request is that you are assuming there must be a "caller" object. But there is no such thing. Your method can be called by methods static

like. directly from an main

application method , but also from class initializers or from constructors even during a constructor call super

, in other words, in places where the object exists in the calling context but hasnt been completely constructed but therefore in a place where hashCode()

it cannot be called.

If you do not consider these gaps in your idea, you should not use Toolkit to Change Caller Byte Codes. It is highly unlikely that you will generate the correct code. Even in places where an instance exists in the call loop, that instance should not be available, and no hash code is computed. What if the get method is called from another method hashCode

?



Practical hurdles aside, the big question is, why do you think you need a caller hash? Whatever you intend to do about it, he can't be right. Think about the following code:

public class Caller {
    public void aMethod() {
        Callee calleeObj = new Callee();
        new Thread(calleeObj::aSpecificMethod).start();
    }
}

      

Whose hash code are you interested in? From an instance of an anonymous class generated at runtime? From an instance Thread

calling a method of run

this anonymous class? Or an instance Caller

that won't be on the call stack at all when you call your method?

+4


source


You must pass either the caller or its hash code as a parameter to the method.



0


source







All Articles