80

I want to convert a web form to a model in Java.

In C# I can write this:

<input name="id" value="" type="text"/>


public class Test
{
    public int? Id{get;set;}
}

The id can be null.

But in Java when using struts2 it throws an exception:

Method "setId" failed

So how to write this case in Java?

cfeduke
  • 23,100
  • 10
  • 61
  • 65
Dozer
  • 5,025
  • 11
  • 36
  • 52

4 Answers4

162

Instead of using int you can use Integer (Integer javadoc) because it is a nullable Java class.

Brent Matzelle
  • 4,073
  • 3
  • 28
  • 27
Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
51

You can use an Integer, which is a reference type (class)in Java and therefore nullable.

Int32 (or int) is a struct (value type) in C#. In contrast, Integer in Java is a class which wraps an int. Instances of reference types can be null, which makes Integer an legit option.

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.

Matthias Meid
  • 12,455
  • 7
  • 45
  • 79
8

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.

DigitalZebra
  • 39,494
  • 39
  • 114
  • 146
1

Optional<Integer> - The purpose of the class is to provide a type-level solution for representing optional values instead of null references.

OptionalInt - A container object which may or may not contain a int value. If a value is present, isPresent() will return true and getAsInt() will return the value.

Denis P.
  • 302
  • 1
  • 2
  • 8