Two Laptop Bag
The moose likes Beginning Java and the fly likes NotNull annotation for Java SE Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "NotNull annotation for Java SE" Watch "NotNull annotation for Java SE" New topic

NotNull annotation for Java SE

Eric Lopez-Fernandez

Joined: Oct 13, 2011
Posts: 17
Hey there,

I am trying to implement an annotation that will function similar to the javax.validation.constraints.NotNull but something that I can use with Java SE.

I have the following annotation but it does not seem to work. Can you please take a look?

Here is the annotation:


import java.lang.annotation.*;

* Designates that a field, return value, argument, or variable is
* guaranteed to be non-null.
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE})
public @interface NotNull {}


Here is the class that will use it:
public class UsingNotNull{

public void notNullMethod(@NotNull String cadena){
public static void main(String... args){
String cadena = "it works!";
String cadenaNula = null;

UsingNotNull unn = new UsingNotNull();

Thanks in advance for your help!

Jeff Verdegan

Joined: Jan 03, 2004
Posts: 6109

Please note that ItDoesntWorkIsUseless.(⇐click)
Rob Spoor

Joined: Oct 27, 2005
Posts: 20273

Just because you create an annotation doesn't mean that the compiler knows what to do with it. For annotations @Deprecated, @Override, @SuppressWarnings and (since Java 7) @SafeVarargs, the compiler has built-in support because the compiler knows these will always exist. This isn't true for custom created annotations. The only way to get that one to work is to create your own compiler that does know that it should treat that annotation specially.

There are IDEs (IntelliJ comes to mind, with its own @NotNull) that have their own compiler with added support for extra annotations - but again, annotations pre-programmed into the compiler.

How To Ask Questions How To Answer Questions
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15082

Did you know that there is a JSR: JSR 305 for these kinds of annotations? You can download the reference implementation for this JSR. A tool such as FindBugs will recognise the annotations defined in this JSR, so it can help you find potential bugs if you use these annotations. If you define your own NotNull annotation, FindBugs (and other tools) ofcourse won't recognise it, so it will be of limited value.

JSR 305 puts a number of annotations in the javax.annotation package. One of the annotations is @Nonnull.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link:
subject: NotNull annotation for Java SE
jQuery in Action, 3rd edition