知道Class中的所有变量是否为空的最佳方法是什么? [英] What is the best way to know if all the variables in a Class are null?

查看:124
本文介绍了知道Class中的所有变量是否为空的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这意味着该类已初始化,但未设置变量。

This would mean that the class was initialized, but the variables were not set.

样本类:

public class User {

    String id = null;
    String name = null;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

实际班级很大,我不想检查每个变量的if(xyz == null)。

The actual class is huge that I prefer not to check if(xyz == null) for each of the variables.

推荐答案

尝试这样的事情:

public boolean checkNull() throws IllegalAccessException {
    for (Field f : getClass().getDeclaredFields())
        if (f.get(this) != null)
            return false;
    return true;            
}

尽管如果可行的话,检查每个变量可能会更好。

Although it would probably be better to check each variable if at all feasible.

这篇关于知道Class中的所有变量是否为空的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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