Hello,
I have found following question: http://stackoverflow.com/questions/41894/0-program-name-in-java-discover-main-class but accepted answer fails in this situation:
public class Derived extends Base { }
class Base {
public static void main(String[] args){
System.out.println(getTheClassName());
}
static String getTheClassName(){
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
StackTraceElement main = stack[stack.length - 1];
return main.getClassName();
}
}
When calling:
java Derived
the output is unfortunately Base
not Derived
as expected.
Is it possible to get the name of real main class? (btw. jps
tool detects main class correctly but to get the proper name I need to know ID of current VM, and that is also a problem)
Best regards.
Edit: to be precise: I need to know what is the name of class passed as command line argument passed to JVM. jps
tools does it the way I want, but I cannot use this tool because of other problems (such as unknown VMid).
Edit2: replying globally to Thorbjørn's answer:
For your approach to work, you need to have a non-static method instead. Make it non-static, have a main() in Derived doing a new Derived().getTheClassName()
I am wondering I can get the name without implementing main method in Derived class.
Solution: I will provide both (Thorbjørn's and erickson's) mechanisms of an initialization of Derived
class ;-) All of the answers were very helpful. I accepted Thorbjørn's becase he posted his answer earlier than erickson. Thank You.