简体   繁体   English

Java中使用其他常量的常量

[英]Constants that use other constants in Java

In my class, I need both an SLF4J Logger with the class as the parameter, as well as a simple class name.在我的 class 中,我需要一个以 class 作为参数的 SLF4J Logger,以及一个简单的 class 名称。 Both the logger and CLASS_NAME constants use MethodHandles.lookup(). logger 和 CLASS_NAME 常量都使用 MethodHandles.lookup()。 I was wondering if it makes more sense/is more efficient to have something like this:我想知道拥有这样的东西是否更有意义/更有效:

private static final Lookup lookup = MethodHandles.lookup();
private static final Logger logger = LoggerFactory.getLogger(lookup.getClass());
private static final String CLASS_NAME = lookup.lookupClass().getSimpleName();

Or just have MethodHandles.lookup() twice:或者只使用 MethodHandles.lookup() 两次:

private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().getClass());
private static final String CLASS_NAME = MethodHandles.lookup().lookupClass().getSimpleName();

Given these two options, I'd choose the second.鉴于这两个选项,我会选择第二个。 There's no reason to maintain a permanent reference to a lookup object if it's never directly needed again.如果不再直接需要它,则没有理由维护对查找 object 的永久引用。 The cost of obtaining the lookup instance is relatively cheap, and this code is only run once -- when the class is initialized.获取查找实例的成本相对较低,而且这段代码只运行一次——当 class 被初始化时。

However, I'm not sure why you're calling lookup in the first place.但是,我不确定您为什么首先调用 lookup 。 The normal pattern here is to use a class literal.这里的正常模式是使用 class 文字。

By the way, if you really needed to reference a throw-away constant, the best approach is to use a static intializer.顺便说一下,如果你真的需要引用一个一次性常量,最好的方法是使用 static 初始化器。

private static final Logger logger;
private static final String CLASS_NAME; 

static {
    var lookup = MethodHandles.lookup();
    logger = LoggerFactory.getLogger(lookup.getClass());
    CLASS_NAME = lookup.lookupClass().getSimpleName();
}

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

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