是否可以从静态方法中获取类名?

发布于 2024-07-26 01:22:02 字数 454 浏览 4 评论 0原文

可能的重复:
从 Java 中的静态方法获取类名

当您在静态方法内部时,有没有一种方法可以获取类名(包含名称的字符串)而无需键入类名本身?

例如,输入 MyClass.class.getName() 并不比输入 "Myclass" 更有用。

Possible Duplicate:
Getting the class name from a static method in Java

When you are inside of a static method, is there a way to get the class name (a string containing the name) without typing the class name itself?

For example, typing MyClass.class.getName() is no more useful than just "Myclass".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

白云悠悠 2024-08-02 01:22:02

您可以使用匿名内部类:

class Test {
  public static void main(String[] args) {
    String className = new Object(){}.getClass().getEnclosingClass().getName();
    System.out.println(className);
  }
}

You can use an anonymous inner class:

class Test {
  public static void main(String[] args) {
    String className = new Object(){}.getClass().getEnclosingClass().getName();
    System.out.println(className);
  }
}
倒带 2024-08-02 01:22:02

您可以通过创建(而不是抛出)新的异常并检查其堆栈跟踪来完成此操作。 您的类将是第零个元素,因为它是异常的起源。 感觉有点不对劲,但它会起作用。

System.out.println( new Exception().getStackTrace()[0].getClassName() );

您可以对 Thread 类执行相同的操作。 这对我来说似乎更干净,但线稍微长一些。 您的类现在是堆栈跟踪中的第一个元素,而不是第零个。 Thread.getStackTrace() 是第零个。

System.out.println( Thread.currentThread().getStackTrace()[1].getClassName() );

例如,键入 MyClass.class.getName() 并不比键入“Myclass”更有用。

相反,如果您使用 IDE 的重构功能重命名 MyClass,它将用 RenamedClass.class.getName() 替换 MyClass.class.getName()。 如果你在里面放了一个字符串,你就必须手动完成。

You can do it by creating (not throwing) a new Exception and inspecting its stack trace. Your class will be the zeroth element as it is the origin of the Exception. It kinda feels wrong, but it will work.

System.out.println( new Exception().getStackTrace()[0].getClassName() );

You can do the same with the Thread class. This seems cleaner to me, but the line is slightly longer. Your class is now the first element in the stacktrace rather than the zeroth. Thread.getStackTrace() is the zeroth.

System.out.println( Thread.currentThread().getStackTrace()[1].getClassName() );

For example, typing MyClass.class.getName() is no more useful than just "Myclass".

On the contrary, if you rename MyClass using your IDE's refactor function it will replace MyClass.class.getName() with RenamedClass.class.getName(). If you put a string in there you'll have to do it manually.

同尘 2024-08-02 01:22:02

如果这只是为了节省一些打字的时间,那么就不要考虑它。 使用 MyClass.class 允许所有重构工具识别您的代码并正常工作。

当你选择用 Java 编程时,你会输入很多内容。 使用 IDE 可以帮助您,这样您就不必输入太多内容了:)

If it is just a matter of saving some typing, then don't think about it. Using MyClass.class allows all refactoring tools to recognize and work properly with your code.

When you choose to program in Java, you WILL type a lot. Use an IDE which will help you so you don't have to type quite as much :)

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