Monday, March 14, 2022

[SOLVED] Java Annotation Processing Tool @NoNull

Issue

I want to create an annotation that restricts a developer from specifying null as a parameter, which has been annotated with @NoNull

For example, if I create this method:

public void printLine(@NoNull String line) {
    System.out.println(line);
}

On a method call, I want an error to appear if the user specifies null for line: printLine(null);

I have been using APT for only a little bit of time, and am wondering how to do this (if possible)?

This is the annotation I have created so far:

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.SOURCE)
public @interface NoNull {}

Solution

Compile time will be tough to check, since you're really dealing with runtime values. If you want to create annotations to automatically add code to check this stuff, you should look at project lombok:

http://projectlombok.org/

It uses an annotation processor to add code to your beans to do various things.

For example:

@Getter @Setter
private int id;

The annotation processor would automatically add get/set methods to your bean.

I don't think it has null checks, but you should be able to add this in and contribute it.

Another option is to use the validation jsr, though this requires you to explicitly validate at runtime, but you could accomplish this with proxies or AOP.

@NotNull @Min(1)
public void setId(Integer id)


Answered By - Matt
Answer Checked By - Senaida (WPSolving Volunteer)