Why, if my class has an org
field, I cannot use @Slf4j
Lombok log annotation. The following code will produce a compilation error at line #3:
MyClass.java:[3,1] non-static variable org cannot be referenced from a static context
import lombok.extern.slf4j.Slf4j;
@Slf4j
class MyClass {
String org;
void printDebug() { log.debug("Org: " + org); }
}
Lombok documentation (projectlombok.org/features/log) claims it adds a single log
field. Why it conflicts with org
?
Replace your:
import lombok.extern.slf4j.Slf4j;
and@Slf4j
with:import static org.slf4j.LoggerFactory.getLogger;
private static final Logger log = getLogger(MyClass.class);
If you, in IntelliJ, do right-click -> Refactor -> Delombok -> @Log (and friends), you'll see the generated fields initialization starts with: = org.slf4j...
:
private static final Logger log = org.slf4j.LoggerFactory.getLogger(MyClass.class);
// ^^^ - this is ambiguous
and this produces the conflict with your org
field:
String org;
// ^^^
Lombok team could work-around this by injecting import org.slf4j.LoggerFactory
, but they might think the demand for the fix is not so high. This is an opinion of a Lombok contributor:
...This is a handicap in the java language that uses the same notation for two completely different concepts. Don't know what could be done in lombok to solve this issue without creating some other issue somewhere else. [REF]