栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Java中是否可以检查对象字段是否为null,然后将默认值添加到所有这些属性?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Java中是否可以检查对象字段是否为null,然后将默认值添加到所有这些属性?

您可以使用反射来遍历对象的字段并进行设置。您显然需要在类型甚至字段名称与所需的默认值之间进行某种映射,但这可以很容易地在循环中完成。例如:

for (Field f : obj.getClass().getFields()) {  f.setAccessible(true);  if (f.get(obj) == null) {     f.set(obj, getDefaultValueForType(f.getType()));  }}

[更新]

使用现代Java,您可以使用注释为每个类设置字段的默认值。完整的实现可能如下所示:

// DefaultString.java:import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;@Retention(RetentionPolicy.RUNTIME)public @interface DefaultString {    String value();}// DefaultInteger.java:import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;@Retention(RetentionPolicy.RUNTIME)public @interface DefaultInteger {    int value();}// DefaultPojo.java:import java.lang.annotation.Annotation;import java.lang.reflect.Field;public class DefaultPojo {    public void setDefaults() {        for (Field f : getClass().getFields()) { f.setAccessible(true); try {     if (f.get(this) == null) {         f.set(this, getDefaultValueFromAnnotation(f.getAnnotations()));     } } catch (IllegalAccessException e) { // shouldn't happen because I used setAccessible }        }    }    private Object getDefaultValueFromAnnotation(Annotation[] annotations) {        for (Annotation a : annotations) { if (a instanceof DefaultString)     return ((DefaultString)a).value(); if (a instanceof DefaultInteger)     return ((DefaultInteger)a).value();        }        return null;    }}// Test Pojopublic class TestPojo extends DefaultPojo {    @DefaultString("Hello world!")    public String stringValue;    @DefaultInteger(42);    public int integerValue;}

然后

TestPojo
只需运行即可设置a的默认值
test.setDetaults()



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/452935.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号