Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

后端 未结 8 529
天涯浪人
天涯浪人 2020-12-05 06:57

I need to make sure that no object attribute is null and add default value in case if it is null. Is there any easy way to do this, or do I have to do it manually by checkin

8条回答
  •  醉话见心
    2020-12-05 07:20

    This is not to check for null, instead this will be helpful in converting an existing object to an empty object(fresh object). I dont know whether this is relevant or not, but I had such a requirement.

    @SuppressWarnings({ "unchecked" })
    static void emptyObject(Object obj) 
    {
        Class c1 = obj.getClass();
        Field[] fields = c1.getDeclaredFields();
    
        for(Field field : fields)
        {
            try
            {
                if(field.getType().getCanonicalName() == "boolean")
                {
                    field.set(obj, false);
                }
                else if(field.getType().getCanonicalName() == "char")
                {
                    field.set(obj, '\u0000');
                }
                else if((field.getType().isPrimitive()))
                {
                    field.set(obj, 0);
                }
                else
                {
                    field.set(obj, null);
                }
            }
            catch(Exception ex)
            {
    
            }
        }
    }
    

提交回复
热议问题