如何在静态方法中获取当前类名

When you produce logging or debugging messages, you often want to include the name of the current class, such as

System.err.println("Something awful happened in " + getClass());

But that fails in a static method. After all, the call to getClass calls this.getClass(), and a static method has no this. Use the following expression instead:

new Object(){}.getClass().getEnclosingClass() // gets class of static method

Here, new Object(){} makes an anonymous object of an anonymous subclass of Object, and getEnclosingClass gets its enclosing class—that is, the class containing the static method.

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,449评论 0 10
  • 1感恩: 感恩今天修整身心,整理衣物,继续断舍离,整理房间,就像整理自己的心,房间整洁,心里也清净多了。 感恩:我...
    遇见念念相续阅读 98评论 0 0
  • 今天游玩了浠水洪山香榭园,连日的阴霾一扫而光。中秋家节的喧嚣已成昨日,喜欢宁静的我终于在这香榭园找到感觉,停顿的思...
    媚影心语阅读 476评论 0 3
  • 电影《肖恩克的救赎》里, 犯人肖恩想在监狱建一个图书馆,很明显,这不是小事,也不是一件容易的事,这事得上面点头才行...
    SHINEIDO阅读 1,987评论 0 2
  • “物是人非”向来无非就是“欲语泪先流”,可越来越发现,大都是物也非人也非,只不过是怀念里的东西,尚可存在罢了。所以...
    念旧的写作人阅读 576评论 0 0