你可以使用Lombok注解来声明方法为toString吗?

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

Can I declare method as toString with lombok annotation

问题

不过我想用一个 Lombok 注解来替换 toString() 方法。该注解的输出结果应与当前代码的输出结果相同。在 Lombok 中是否有实现这样功能的方法呢?

英文:

Is it possible to declare a certain function foo() as toString ? Concretely:

int property 1;
int property 2;
int property 3;

boolean bar() {...}

int foo(){
  return bar() ? 0 : property2;
}

@Override
public String toString() {
  return String.valueOf(foo());
}

Now I want to replace the toString() with a Lombok annotation. Which has the same output as the current one. is this somehow possible with Lombok?

答案1

得分: 4

以下是翻译好的内容:

整个 lombok 的目的是为您“编写代码” - 如果您已经编写了代码,为什么还需要这个?

您可以在您的 foo() 方法上放置 @ToString.Include 注解,这会导致 lombok 列出调用此方法的结果以及所有字段。如果您的方法与您的某个方法同名(或者在方法名前面加上 get 并大写第一个字母后与方法名相同),方法的输出将替换该字段。然后,您可以在 @ToString 上放置一个标记,表示您只想要显式包含的内容,此时 lombok 的 toString 将输出类似于: "YourClass(foo=12)"

@ToString(onlyExplicitlyIncluded=true)
public class YourClass {
    int property1, property2, property3;

    @ToString.Include
    int foo() {
        return bar() ? 0 : property2;
    }
}
英文:

The whole point of lombok is to 'write code for you' - if you've already written it, why would you want this?

What you can do is put a @ToString.Include annotation on your foo() method, which will cause lombok to list the result of invoking this method along with all the fields. If your method has the same name as one of your methods (or the same name after putting get in front and capitalizing the first letter), the method's output replaces that field. You can then put a marker on @ToString to say that you only want explicitly included stuff, at which point lombok's toString will emit something like: "YourClass(foo=12)":

@ToString(onlyExplicitlyIncluded=true)
public class YourClass {
    int property1, property2, property3;

    @ToString.Include
    int foo() {
        return bar() ? 0 : property2;
    }
}

huangapple
  • 本文由 发表于 2020年9月14日 16:36:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63880829.html
匿名

发表评论

匿名网友

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

确定