[英]How to do this C# return statement in Java
I will like to know if there is a way to do the second or third return statement in Java我想知道是否有办法在Java中做第二个或第三个return语句
Example using C#:使用 C# 的示例:
I have this class with properties我有这个带有属性的 class
class Properties
{
public int ResponseCode { get; set; }
public string ResponseMessage { get; set; }
public string Name { get; set; }
public string Academics { get; set; }
}
I did it like this at the beginning:一开始我是这样做的:
public static Properties CreateStudentFirstWay()
{
Properties properties = new Properties();
properties.Name = "Michael";
properties.Academics = "Information";
properties.ResponseCode = 0000;
properties.ResponseMessage = "Created";
return properties;
}
I use this from time to time我不时使用这个
public static Properties CreateStudentSecondWay()
{
Properties properties = new Properties()
{
Name = "Michael",
Academics = "Information",
ResponseCode = 0000,
ResponseMessage = "Created"
};
return properties;
}
And recently I have been doing it like this最近我一直在这样做
public static Properties CreateStudentThirdWay()
{
return new Properties()
{
Name = "Michael",
Academics = "Information",
ResponseCode = 0000,
ResponseMessage = "Created"
};
}
We are able to do the last one in C# without a constructor, without a builder or even without the need to populate all the properties in the class.我们能够在 C# 中完成最后一个,无需构造函数,无需构建器,甚至无需填充 class 中的所有属性。
Is there a way to accomplished this in Java without the need of a constructor or the builder?有没有一种方法可以在 Java 中完成此操作而无需构造函数或生成器?
Thanks!谢谢!
Java does not support this syntax; Java 不支持这种语法; you have to use a variable and call the various set
methods.您必须使用变量并调用各种set
方法。 Groovy does have a syntax that provides this: Groovy 确实具有提供此功能的语法:
public static Properties createStudent() {
return new Properties(
name: "Michael",
academics: "Information",
responseCode: 0,
responseMessage: "created"
)
}
but if you want to do this with Java you'll need either a constructor with arguments or a builder.但是,如果您想使用 Java 执行此操作,则需要使用 arguments 的构造函数或构建器。 Lombok's @AllArgsConstructor
can generate one for you. Lombok 的@AllArgsConstructor
可以为您生成一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.