简体   繁体   中英

lombok log annotation is not working for static methods

I am trying to use lombok's @Slf4j annotation. It works fine for non-static methods but I am unable to use them for static ones, eg:

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MyClass {

    public static void staticMethod() {
        log.info(""); //build error
        //code
    }

    public void nonStaticMethod() {
        log.info(""); //builds ok
        //code
    }

More specifically the build error is:

Error:(17, 9) java: non-static variable log cannot be referenced from a static context

So either I am missing something or this simply is not the way to do it, but what is causing me some confusion is that other answers seem to indicate that this usage is the correct one. Does anyone know what am I doing wrong? Thank you for your help.

Check with Delombok what exactly does lombok generate in your case.

Usually the logger should be a static field.

However there is a configuration:

lombok.log.fieldIsStatic = [true | false] (default: true)

From the documentation: Normally the generated logger is a static field. By setting this key to false, the generated field will be an instance field instead.

Of course if the field is non-static you can't use it from the static method as usual in java

A link to documentation

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