gpt4 book ai didi

java - 如何在 Java 中执行此 C# return 语句

转载 作者:行者123 更新时间:2023-12-01 16:58:18 24 4
gpt4 key购买 nike

我想知道是否有办法在 Java 中执行第二个或第三个 return 语句

使用 C# 的示例:

我有这个带有属性的类

class Properties
{
public int ResponseCode { get; set; }

public string ResponseMessage { get; set; }

public string Name { get; set; }

public string Academics { get; set; }
}

我一开始是这样做的:

    public static Properties CreateStudentFirstWay()
{
Properties properties = new Properties();
properties.Name = "Michael";
properties.Academics = "Information";
properties.ResponseCode = 0000;
properties.ResponseMessage = "Created";
return properties;
}

我有时会使用这个

    public static Properties CreateStudentSecondWay()
{
Properties properties = new Properties()
{
Name = "Michael",
Academics = "Information",
ResponseCode = 0000,
ResponseMessage = "Created"
};

return properties;
}

最近我一直在这样做

    public static Properties CreateStudentThirdWay()
{
return new Properties()
{
Name = "Michael",
Academics = "Information",
ResponseCode = 0000,
ResponseMessage = "Created"
};
}

我们可以在 C# 中完成最后一项,无需构造函数、构建器,甚至无需填充类中的所有属性。

有没有一种方法可以在 Java 中完成此任务,而不需要构造函数或构建器?

谢谢!

最佳答案

Java不支持这种语法;您必须使用变量并调用各种 set 方法。 Groovy 确实有提供此功能的语法:

public static Properties createStudent() {
return new Properties(
name: "Michael",
academics: "Information",
responseCode: 0,
responseMessage: "created"
)
}

但是如果您想使用 Java 来执行此操作,您将需要一个带参数的构造函数或一个构建器。 Lombok 的 @AllArgsConstructor 可以为您生成一个。

关于java - 如何在 Java 中执行此 C# return 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61554288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com