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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:26:05  来源:igfitidea点击:

How to write nullable int in java?

c#javanullable

提问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 idcan 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 intyou 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, Integerin Java is a class which wrapsan int. Instances of reference types can be null, which makes Integeran 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 Integersince 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 Integerinstead of int. This is essentially a nullable int. I'm not too familiar with Struts, but using Integershould allow you to omit the value.

在 Java 中,只需使用Integer而不是int. 这本质上是一个可为空的 int。我对 Struts 不太熟悉,但是 usingInteger应该允许您省略该值。