AWS Lambda构造函数重载Java POJO

时间:2018-11-08 22:45:36

标签: java amazon-web-services aws-lambda overloading pojo

我基于以下网址创建了一个Lambda:https://docs.aws.amazon.com/lambda/latest/dg/java-handler-io-type-pojo.html。主要分为三类:

package example;

import com.amazonaws.services.lambda.runtime.Context; 
import com.amazonaws.services.lambda.runtime.RequestHandler;

public class HelloPojo implements RequestHandler<RequestClass, ResponseClass>{   

public ResponseClass handleRequest(RequestClass request, Context context){
    String greetingString = String.format("Hello %s, %s.", request.firstName, request.lastName);
    return new ResponseClass(greetingString);
}
}

是Lambda处理程序。

package example;

 public class RequestClass {
    String firstName;
    String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public RequestClass(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public RequestClass() {
    }
}

是requestClass。

package example;

 public class ResponseClass {
    String greetings;

    public String getGreetings() {
        return greetings;
    }

    public void setGreetings(String greetings) {
        this.greetings = greetings;
    }

    public ResponseClass(String greetings) {
        this.greetings = greetings;
    }

    public ResponseClass() {
    }

}

是响应类。

输入类似于:

{ "firstName": "John", "lastName": "Doe" }  

话虽如此,我对RequestClass确实有一些疑问。现在,它取决于输入中是否提供了firstName和lastName。但是,假设仅提供了一个firstName,并且我想在RequestClass中使用仅一个firstName参数的另一个构造函数,并将lastName初始化为默认的lastName,例如

public RequestClass(String firstName) {
        this.firstName = firstName;
        this.lastName = "defaultLastName";
    }

当我尝试沿着这些行执行某些操作并访问handleRequest中的变量时,我能够获取firstName,但lastName始终为null(猜测是因为我未将其作为输入的一部分提供)。为什么会发生这种情况以及我可以怎么做,以便在访问处理程序类中的lastName时能够得到“ defaultLastName”而不是null的任何原因?

如果需要进一步澄清,请告诉我,我不经常发布到StackOverflow,并且要确保我的问题适当!

1 个答案:

答案 0 :(得分:0)

您可以在默认构造函数中设置一些默认值。

public RequestClass() {
  firstName = "defaultFirstName";
  lastName = "defaultLastName;
}

然后使用 this 调用您的参数化构造函数。

public RequestClass(String firstName) {
  this();
  this.firstName = firstName;
}

有关构造函数重载的读数: https://beginnersbook.com/2013/05/constructor-overloading/