在Java中更改对象参数的值

时间:2018-05-10 07:06:11

标签: java parameter-passing

我有一个代码,我会在每个Rest Service上重复这样的代码:

user = getUserByToken(request.getToken());
if (user == null) {
    response = this.buidResponse(Response.status(Status.UNAUTHORIZED));
}else{
    do things...
} 
return response;

我想创建一种避免重复前4行的方法,例如:

bool validateUser(String token, User userOut, Response responseOut){
    userOut = getUserByToken(token);
    if (userOut == null) {
        responseOut = this.buidResponse(Response.status(Status.UNAUTHORIZED));
    return false;
  }
  return true;

}

但是,由于Java参数是通过value-ref传递的,因此参数不会将其值保持在方法之外......

我有什么替代方案?

1 个答案:

答案 0 :(得分:1)

您可以创建一个包装类MyDTO并将参数保留为字段。 请参考以下代码:

  class MyDTO{
      String token;
      User userOut;
      Response responseOut;

    public String getToken() {
      return token;
    }

    public void setToken(String token) {
      this.token = token;
    }

    public String getUserOut() {
      return userOut;
    }

    public void setUserOut(String userOut) {
      this.userOut = userOut;
    }

    public Response getResponseOut() {
      return responseOut;
    }

    public void setResponseOut(Response responseOut) {
      this.responseOut = responseOut;
    }
  }

bool validateUser(MyDTO dto){
    dto.setUserOut(getUserByToken(dto.getToken()));
    if (dto.getUserOut() == null) {
        dto.setResponseOut(this.buidResponse(Response.status(Status.UNAUTHORIZED)));
    return false;
  }
  return true;
}