86

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?

2

4 Answers 4

175

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

Sign up to request clarification or add additional context in comments.

2 Comments

thanks~ 'int' is same as 'Integer' in C#,so I didn't know this solution.
@Dozer don't forget to mark this post as an answer once the 15 mins have past.
53

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.

1 Comment

this is a more thorough answer than the accepted one
9

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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.