Thread.getAllStackTraces()
may work. - Or walk up the ThreadGroup
hierarchy to the top and get all threads from the root ThreadGroup
(getParent() == null
).
Then examining the stack traces for the main()
method and figuring out its package/class name may help you.
Detecting the 'stand-alone' mode is easy: When your main()
method is run before your other code you're stand-alone.
public class MyMainClass {
private static boolean standalone = false;
public static boolean isStandalone() {
return standalone;
}
public static void main(String[] args) {
standalone = true;
// Run as usual...
}
}
Then any of your code can call MyMainClass.isStandalone()
to figure out if it's running on its own or not.
Determining which application is running your code, when it's not in stand-alone mode, is somewhat harder and probably cannot be done without stack traces, which is not always fully reliable but rather some kind of heuristics.
If you know which classes are present in application B but not in C and vice versa, you can also try to locate one of them via Class.forName()
; if that call fails with a ClassNotFoundException
you know the class in question is not available in the current runtime environment, and may be able to deduce which application is running.
It would certainly be a better idea to define some kind of application-global property for each application which can then be evaluated by your code.