Is there a way to determine who invoked a java class? Lets say its a shell script ... can I find out where it is and who invoked it? in my java program of course ... I'm assuming not since it wouldn't be as straight forward with rmi calls or other remote invokations.
There's no way to do this with straight Java. If a platform-dependent solution was OK, you could either use Runtime.exec() to execute something like "/usr/bin/whoami" and check the output, or you could use JNI to access the host OS's facilities for finding out about a process.
I see two ways to interpret this. One is "who outside the current JVM was responsible for starting the JVM? EFH has given the answer to this question. The other interpretation is "within this JVM, what other class/method/line number called the code currently being executed?" If that's what you want, you're in better luck; Java does provide a reasonably decent way to get this info (though it's not guaranteed to always work):
I selected traces because traces gives a location inside the whoCalled() method; traces gives the location from which you called the whoCalled() method (which you usually know alread), and traces  is the code that called the method containing the whoCalled() method. Modify as necessary depending what you really want. Note also that some stack trace elements may turn out to be null, perhaps because the JVM has done some optimization, or because the .class file does not contain enough debugging info. (I think it helps if you compile with -g; not sure though.) Anway, this is worth a shot though. If you can't use JDK 1.4, well, you can do something like the above using printStackTrace() to a PrintWriter wraping a StringWriter - then extract the string and parse it to look at the stack trace. But it's ugly and less reliable than the code given above.
Originally posted by Joe Shamana: Is there a way to determine who invoked a java class? Lets say its a shell script ... can I find out where it is and who invoked it? in my java program of course ... I'm assuming not since it wouldn't be as straight forward with rmi calls or other remote invokations.
JFH is wrong, because you write 'it's a shell script' and 'whoami' is returning a username. JY is wrong too, because tracing shows you which class called another, and a class is no shellscript. What if your application isn't started via shell-script, but from commandline? I guess you need to solve this problem another way. Perhaps the script could tell your main, where it is?
Why do you need to know the starting script? Perhaps there are some OS-dependent tricks to figure it out, but then we should know more of the context of the problem. Do you assume somebody could be interested in faking the scriptname? Would this make sense in some circumstances? Does your program need to be OS-independent? Whereas -> The directory is quiet easy to determine: