获取Java中使用的调用名称

发布于 2024-07-16 14:22:18 字数 532 浏览 13 评论 0原文

我正在尝试找到一种通用方法来复制此 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

街角迷惘 2024-07-23 14:22:18

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.

奢望 2024-07-23 14:22:18

我唯一能想到的是,确定哪个线程是主线程,获取该线程的堆栈跟踪,然后返回堆栈顶部并询问元素的类名和方法名以查看它是否是主线程。你想要什么。

不过这实在是太恶心了。 我会重新考虑最初的要求,看看是否没有更直接的方法来实现你想要的。

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.

厌味 2024-07-23 14:22:18

我认为这是不可能的。 打印此内容的最简单方法是使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文