@Slf4j produces `non-static variable org cannot be referenced` if the class has `org` field

huangapple go评论67阅读模式
英文:

@Slf4j produces `non-static variable org cannot be referenced` if the class has `org` field

问题

代码部分不要翻译,只返回翻译好的部分:

如果我的类有一个 org 字段,为什么我不能使用 @Slf4j Lombok 日志注解。以下代码将在第3行产生编译错误:

MyClass.java:[3,1] 无法从静态上下文引用非静态变量 org

导入 lombok.extern.slf4j.Slf4j;

@Slf4j
class MyClass {
String org;

void printDebug() { log.debug("Org: " + org); }
}

Lombok 文档(projectlombok.org/features/log)声称它添加了一个单一的 log 字段。为什么它会与 org 冲突呢?

英文:

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?

答案1

得分: 4

如果您在IntelliJ中执行右键单击 -> Refactor -> Delombok -> @Log(以及类似选项),您会看到生成的字段初始化如下: = org.slf4j...

private static final Logger log = org.slf4j.LoggerFactory.getLogger(MyClass.class);
//                                ^^^ - 这是不明确的

这会与您的 org 字段产生冲突:

String org;
//     ^^^

Lombok团队可以通过注入 import org.slf4j.LoggerFactory 来解决这个问题,但他们可能认为修复的需求不是很高。这是Lombok贡献者的观点:

> ...这是Java语言中的一个障碍,它对两个完全不同的概念使用相同的符号。不知道在Lombok中该如何解决这个问题,而不会在其他地方产生问题。[REF]

解决方案:所以,如果您的情况中有 org 字段,只需将:

  • import lombok.extern.slf4j@Slf4j;
  • @Slf4j

替换为:

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]

SOLUTION: So, in cases you have org field, just replace your:

  • import lombok.extern.slf4j.Slf4j; and
  • @Slf4j with:

import static org.slf4j.LoggerFactory.getLogger;



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

huangapple
  • 本文由 发表于 2020年8月29日 23:36:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63648782.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定