简体   繁体   中英

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. Both the logger and CLASS_NAME constants use 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:

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. The cost of obtaining the lookup instance is relatively cheap, and this code is only run once -- when the class is initialized.

However, I'm not sure why you're calling lookup in the first place. The normal pattern here is to use a class literal.

By the way, if you really needed to reference a throw-away constant, the best approach is to use a static intializer.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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