command line – Getting the Invocation Name Used in Java – Education Career Blog

I’m trying to find a generic way to replicate this C functionality:

int main(int argc, char** argv){
    fprintf(2,"%s: error you did something wrong.\n", argv0);
    return 1;
}

in java. So far the only way was to hardcode this into the app, which is ugly. I’d like to get something similar to:

someObj.getClass().getSimpleName();

inside my static main, without referring back to my own class.

Is this even possible?

Edit

My searching for a good hour didn’t turn this one up.

Duplicated question, see $0 (Program Name) in Java? Discover main class? for answer

,

The way java finds the class in which to run static void main() is by the name passed to the java executable (and the classpath). So it’s not possible to have main run unless the right name was passed.

*Well, unless the main that is found calls something like “FooBar.main()” or uses the class loader to find it.

Even then, as main is static and static functions aren’t virtual, the whatever main is called is called because main was called on that class. So in your code, the name (which inn’t passed in the args to main) in just the name of the class that main function is in.

So there’s never an error, and so never need to find the name.

,

The only thing I can think of is that you determine which Thread is the main thread, get the stack trace of that thread and then walk back to the top of the stack and interrogate the class name and method name of the element to see if it’s what you want.

That’s pretty icky though. I’d reconsider the original requirement and see if there’s not a more straight-forward means of achieving what you want.

,

I don’t think this is possible. The easiest way to print this is using MyClass.class.getSimpleName(), or you could create (not throw) a Throwable, print the stack trace, and go from there.

Leave a Comment