“Serializable”类中的字段应该是瞬态的或可序列化的squid:S1948

时间:2016-08-06 10:30:29

标签: java sonarqube serializable

当我使用SonarQube检查我的Java代码时,会弹出一些警告:“Serializable”类中的字段应该是瞬态的或可序列化的squid:S1948。 enter image description here

我的代码:

public class ServiceResult implements Serializable {
    public static final Integer INTERNAL_ERROR = 500;
    public static final Integer SERVICE_EXCEPTION = 501;
    public static final Integer PARAM_ERROR = 999;
    public static final int AUTHORITY_ERROR = 401;
    public static final Integer SUCCESS = 200;
    public static final Integer INPUT_ERROR = 402;

    private Integer code = SUCCESS;
    private Object msg;

    public ServiceResult() {

    }

    public ServiceResult(Integer code, Object msg) {
        this.code = code;
        this.msg = msg;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public Object getMsg() {
        return msg;
    }

    public void setMsg(Object msg) {
        this.msg = msg;
    }

    public static ServiceResult fail(String msg) {
        ServiceResult serviceResult = new ServiceResult();
        serviceResult.setCode(INTERNAL_ERROR);
        serviceResult.setMsg(msg);
        return serviceResult;
    }

    public static ServiceResult success(Object msg) {
        ServiceResult serviceResult = new ServiceResult();
        serviceResult.setCode(SUCCESS);
        serviceResult.setMsg(msg);
        return serviceResult;
    }
}

我只是不确定我还能在这里做什么,Class是可序列化的,并且确实拥有可序列化的所有成员字段。

如果之前已经解决了这个问题,请告诉我。

1 个答案:

答案 0 :(得分:0)

此SonarQube规则要求可序列化类的所有字段也必须可序列化(或标记为transient,以便在序列化期间忽略它们。

Object类未实现Serializable,因此以下行违反了该规则:

private Object msg;

要解决此问题,请将msg从序列化中排除transient,或将类型从Object更改为String或其他任何实现{{1}的类}}