Maheswaran Ravisankar
Maheswaran Ravisankar

Reputation: 17920

Find which class created me

I have a generic component (a simple java package). I convert it into a jar and give it to my clients.

My client can use this jar for any of his applications. Will it be possible to identify who calls my component. That's in my component, will I be able to identify who created an instance of me?

Sorry, If I put this is a vague manner. Given a object I could find the className associated to it using(getClass()) . But I am not sure, if my requirement is ever possible.

Upvotes: 2

Views: 135

Answers (2)

João Mendes
João Mendes

Reputation: 1425

You can get the stack trace of the current thread and parse the StackTraceElements in the return, to find out which methods are calling yours.

You can check out this question here in SO.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1499730

That's in my component, will I be able to identify who created an instance of me?

Not in general, no. You could try obtaining a stack trace in the constructor, but that's not necessarily reliable or helpful.

If you want some sort of identifier, I suggest you have that as a constructor parameter (or factory method parameter). In other words, get the caller to identify themselves.

Upvotes: 5

Related Questions