简体   繁体   English

如何简化类级记录器的创建?

[英]How can I simplify the creation of class-level loggers?

Is there a way in Java to find out which class I'm in without referencing an object? Java 中有没有办法在不引用对象的情况下找出我所在的类? I need the current class name from a static point.我需要静态点的当前类名。 Here is an example:下面是一个例子:

public class MyClass {
  // is this possible?
  private static final String myClassName = ???;

  // not like this
  void someMethod(){
    String className = this.getClass();
  }

  // or this
  private static final String myClassName = MyClass.class;

}

The overall problem is logging.总体问题是日志记录。 The logger of the project I'm working on needs the class name and is supposed to be declared like this:我正在处理的项目的记录器需要类名,并且应该像这样声明:

private static final Logger LOGGER = LogHelper.getLogger(MyClass.class);

If there is a more generic way, it would be easier to copy the logger.如果有更通用的方法,复制记录器会更容易。

I need this code in multiple classes, and it would be nice to just copy the code instead of always replacing "MyClass.class" every time.我需要在多个类中使用此代码,最好只复制代码而不是每次都替换“MyClass.class”。

Unfortunately, different approaches wouldn't be compatible with the conventions of this project.不幸的是,不同的方法与这个项目的约定不兼容。

Some compilers like eclipse lets you do it, for exsamples look this page:一些像 eclipse 这样的编译器可以让你这样做,exsamples 看看这个页面:

http://www.ibm.com/developerworks/opensource/tutorials/os-eclipse-code-templates/ http://www.ibm.com/developerworks/opensource/tutorials/os-eclipse-code-templates/

and use this in your new template:并在您的新模板中使用它:

private static final Logger LOGGER = LogHelper.getLogger(${primary_type_name}.class

To put it simply, there likely isn't a simpler or more generic approach to doing this.简而言之,可能没有更简单或更通用的方法来做到这一点。 While I'm uncertain of the exact logger library you're using, the main fact remains that you must supply the class that you want to log to the logger.虽然我不确定您使用的确切记录器库,但主要的事实仍然是您必须提供要记录到记录器的类。

It does mean extra typing, but there's no realistic approach that is simpler, easier to understand, or safer - anything that's overly complex and uses a lot of reflection to extract the class name would need to be tested to ensure that it always returns the correct class, which is substantially more effort than simply using MyClass.class .这确实意味着额外的输入,但没有更简单、更容易理解或更安全的现实方法——任何过于复杂并使用大量反射来提取类名的东西都需要进行测试以确保它始终返回正确的类,它是比单纯使用基本上更多的努力MyClass.class

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM