C# 如何在java中编写可为空的int?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14321175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write nullable int in java?
提问by Dozer
I want to convert a web form to a model in Java.
我想将 Web 表单转换为 Java 模型。
In C# I can write this:
在 C# 中,我可以这样写:
<input name="id" value="" type="text"/>
public class Test
{
public int? Id{get;set;}
}
The id
can be null.
在id
可以为空。
But in Java when using struts2 it throws an exception:
但是在 Java 中使用 struts2 时会抛出异常:
Method "setId" failed
So how to write this case in Java?
那么如何用Java编写这个案例呢?
采纳答案by Ivaylo Strandjev
Instead of using int
you can use Integer
(Integer javadoc) because it is a nullable Java class.
int
您可以使用Integer
( Integer javadoc)而不是使用,因为它是一个可为空的 Java 类。
回答by Matthias Meid
You can use an Integer
, which is a reference type (class)in Java and therefore nullable.
您可以使用Integer
,它是 Java 中的引用类型(类),因此可以为 null。
Int32
(or int
) is a struct (value type) in C#. In contrast, Integer
in Java is a class which wrapsan int
. Instances of reference types can be null
, which makes Integer
an legit option.
Int32
(或int
) 是 C# 中的结构体(值类型)。与此相反,Integer
在Java是其中的一类包装的int
。引用类型的实例可以是null
,这是Integer
一个合法的选择。
Nullable<T>
in .NET gives you similar options because it enables you to treat a value type like a nullable type. However, it's still different from Java's Integer
since it's implemented as a struct (value type) which can be compared to null
, but cannot actually hold a genuine null reference.
Nullable<T>
在 .NET 中为您提供了类似的选项,因为它使您能够将值类型视为可空类型。然而,它仍然与 Java 不同,Integer
因为它是作为一个结构体(值类型)实现的,它可以与 比较null
,但实际上不能保存真正的空引用。
回答by Polaris878
In Java, just use Integer
instead of int
. This is essentially a nullable int. I'm not too familiar with Struts, but using Integer
should allow you to omit the value.
在 Java 中,只需使用Integer
而不是int
. 这本质上是一个可为空的 int。我对 Struts 不太熟悉,但是 usingInteger
应该允许您省略该值。