如何使用Lombok @ToString跳过空字段 [英] How to skip null field with lombok @ToString

查看:715
本文介绍了如何使用Lombok @ToString跳过空字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有成功地将lombok @toString与跳过null字段行为一起使用的简单方法.

I found with no succes the simple way to use lombok @toString with the skip null field behaviour.

我认为可以使用方面编程为所有函数创建自己的toString函数.像这样我可以检查所有空字段并跳过它.

I think create my own toString function for all function using the aspect programmation. Like that i can chek all null field and skip that.

但这是一个好习惯,还是lombok @toString可以简单地做到这一点?

But it is the good practice, or lombok @toString has one option to do that simply?

最好的问候

推荐答案

您可以覆盖如下的toString方法

You can override toString method like below

public class MyClass{

field a;
field b;

@Override
public String toString() {
    Field[] fields = MyClass.class.getDeclaredFields();
    String res = "";
    for(int x = 0; x < fields.length; x++){
        try {
            res += ( fields[x].get(this)) != null ? fields[x].getName() + "="+ (fields[x].get(this).toString()) + "," : "";
        } catch (Exception ex) {
            
        } 
    }
    return res;
}

这篇关于如何使用Lombok @ToString跳过空字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆