获取Java中使用的调用名称
我正在尝试找到一种通用方法来复制此 C 功能:
int main(int argc, char** argv){
fprintf(2,"%s: error you did something wrong.\n", argv[0]);
return 1;
}
在 java 中。 到目前为止,唯一的方法是将其硬编码到应用程序中,这很丑陋。 我想得到类似的东西:
someObj.getClass().getSimpleName();
在我的静态 main 中,而不引用我自己的类。
这可能吗?
编辑
我搜索了一小时并没有找到这个。
重复的问题,请参阅 Java 中的 $0 (程序名称)? 发现主类? 寻求答案
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", argv[0]);
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
java 查找要在其中运行 static void main() 的类的方式是通过传递给 java 可执行文件(和类路径)的名称。 因此,除非传递了正确的名称,否则不可能进行主运行。
*好吧,除非找到的 main 调用类似“FooBar.main()”的东西或使用类加载器来查找它。
即使如此,由于 main 是静态的并且静态函数不是虚拟的,因此调用任何 main 都会被调用,因为 main 是在该类上调用的。 因此,在您的代码中,名称(不会将参数传递给 main)只是
main
函数所在类的名称。因此永远不会出现错误,因此永远不需要找到名字。
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.
我认为这是不可能的。 打印此内容的最简单方法是使用 MyClass.class.getSimpleName(),或者您可以创建(而不是抛出)Throwable,打印堆栈跟踪,然后从那里开始。
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.