In what order are Java constraints being executed - java

I have a Java method in which the method itself is annotated with a constraint (cross-parameter) and the arguments are also annotated with constraints (#NotNull, #NotEmpty etc).
Is the method constraint validated after method argument validation or is the order of validation not specified?

Annotations don't inherently do anything. They just mark things. javac itself knows what #Deprecated and #Override and #FunctionalInterface mean, but the effects are always to either do nothing, or to generate a compiler error: These annotations do not cause the compiler to generate any code.
Aside from Project Lombok this is a general principle of annotations, and even Project Lombok is an annotation processor: You have to put lombok on your classpath during a compilation, or nothing happens.
In other words, it is not possible for the #NonNull annotation in your code to generate any null check all on its own. The constraints are applied elsewhere, or by a code generating annotation processor that you explicitly include by putting it on the classpath or passing it along as annotation processor. For example, it IS possible for code you invoke to introspect your method and notice things. Thus, you could for example have:
class Example {
#NotEmpty String name;
}
and then you can do:
new Example("");
and this won't cause an exception. But you could do:
Validator validator = SomeHypotheticalValidationLibrary.newValidator();
validator.validate(new Example(""));
and then this validator would produce an error stating that the instance you provided fails verification. This is an example of annotations being introspected.
And now to answer your question:
The order in which such constraints are validated depends entirely on the validation library you use to do the validation; out of the box, the annotation itself does not and cannot produce any validation code. You'd have to check the documentation of your validation library, and provide the context within which you are validating.
If you're talking specifically about lombok's #NonNull - lombok scans your code for null checks (either of the form if (x == null) throw new Something(); or of the form Objects.nullCheck or guava's nullcheck). If it finds a nullcheck for an #NonNull annotated parameter, lombok does nothing. If it doesn't, it generates a nullcheck after all your explicit null checks. Lombok stops scanning for nullchecks once it hits a line that is NOT a nullcheck (so, neither an if (x == null) nor a methodInvocation(x, "optional text");). #NonNull is currently the only annotation that causes lombok to generate validation code (there is no #lombok.NotEmpty).
We may be able to give more insights if you explain which annotation processors / validation frameworks you are using.

Related

Annotation that throws an exception if the conditions are not met

My class has is a boolean variable, by default, it has the value false, during execution it can change to true. There are also methods that can only be called when the variable is true.
I want to do something like:
#ConfirmedOnly
public void method() {
// some code
}
It will throw an exception when variable is not true.
Do I have to write an annotation handler like Lombok?
In order to give behavior to an annotation, you must write an annotation processor. (Lombok is an example of an annotation processor.)
An annotation is not a method that gets called at run time. It is a marker in the source code with no behavior. (The Java Language Specification section 9.7 says "An annotation is a marker which associates information with a program construct, but has no effect at run time.") An annotation processor gives it behavior. The annotation processor operates at compile time, for example by issuing errors or by changing the source code.

Can I make IntelliJ #NonNull/Nullable annotations act like Eclipse

Summary:
Is there any way to configure IntelliJ to not add errors to existing un-annotated code but NEVER allow a null to be passed into a #NonNull parameter?
Details: Eclipse actually has 3 "nullable" states, #NonNull, #Nullable and Unannotated.
IntelliJ appears to have 2 types of nullable, you treat Un-annotated as either #NonNull or #Nullable, Un-annotated does not have it's own behavior.
All three states are pretty important if you have a large existing project and want to start using the annotations.
Question: Am I missing a configuration option or are the annotations assumed to be an all-or-nothing in IntelliJ?
tl;dr: (why all three types are needed)
In eclipse the Un-annotated will act as:
#NonNull when interacting with other Un-Annotated items
#Nullable when being passed to something annotated with #NonNull
The first is needed so that warnings will not be created on existing un-annotated code like "str.length()"
The second is so that you will be warned if you attempt to pass an untyped potential null to a method annotated with #NonNull.
This combination allows you to slowly push annotations through your otherwise un-annotated code.
In Intellij an option called "Treat non-annotated members and parameters as #Nullable defines the behavior of un-annotated variables/code, if this is off they act as either #Non-Null, if it's on they are #Nullable.
Turning on the "Treat as #Nullable" option is great if you assume your entire codebase is annotated, but if you are working with existing code it will cause endless warnings in un-annotated cases like this:
public void test(String s) {
System.out.println(s.length());
}
public void callTest(String maybeNull) {
test(maybeNull);
}
If I use IntelliJ's setting specifying that un-annotated should be treated as Nullable, this un-annotated code gains a warning because s is nullable and must be null-checked before s.length() can be called. I don't want to see that kind of warning throughout my code until I'm ready to add the annotations.
On the other hand, If I assume the default settings then when I start to apply annotations by changing this line:
public void test(#NonNull String s) {
It does NOT cause the expected error in the caller because IntelliJ assumes that the un-annotated maybeNull should be treated as #NonNull. We absolutely want a warning here because maybeNull actually could be null--otherwise the annotations aren't doing anything for us.

Immutables lib adds #Nullable to equals() method

I have a very simple class and using Immutables library. The auto-generated code defines equals method like so:
#Override
public boolean equals(#Nullable Object another) {
The #Nullable annotation causes the following FindBugs error:
NP_METHOD_PARAMETER_TIGHTENS_ANNOTATION: Method tightens nullness
annotation on parameter
A method should always implement the contract of a method it
overrides. Thus, if a method takes a parameter that is marked as
#Nullable, you shouldn't override that method in a subclass with a
method where that parameter is #Nonnull. Doing so violates the
contract that the method should handle a null parameter.
I am using Immutables-value-2.5.6.jar
Has anyone seen this error?
I have mitigated the issue temporarily by adding:
#SuppressFBWarnings
to the Immutables class. But I don't think this is a long term solution. There must be something else I am missing.
This appears to be an open bug in the FindBugs project (https://sourceforge.net/p/findbugs/bugs/1385/), so I would say that disabling the warning using an annotation is fine until the next release.
This class suggests that the SpotBugs project, which is the successor to FindBugs, have addressed the issue. Perhaps consider migrating?
Update : The FindBugs issue has since been closed.

Java annotations: make #NotNull

I am learning Java annotations and I want to design a annotation like #NotNull which enforces compiler to throw an error on following:
#NotNull
private String myVar = null;
Now, I am not getting any lead in what to write in the body of the annotation:
#interface NotNull{
// what goes here
}
Can I design such a functionality using Annotations or I have read it all wrong? I am looking at the checker package and it contains one such annotation.
You can only define the "meta" properties themselves in annotations, no actual logic
For compile-time annotation logic you need to write an annotation-processor (regular java-code that gets executed during compilation and allows you to examine annotated elements using reflection), during runtime you can use the regular reflection API

Java Annotation Processing Tool #NoNull

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 {}
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)
The point isn't to use the annotation only for readability, but to enforce the annotation at compile-time with APT
Considering that null is a runtime artifact, I don't see how you will enforce a null check at "compile time."
Instead, you'll have to modify your classes, and apt is not the tool to do this, at least not by itself. It exists to extract information about annotated elements from source files. But to enforce your #Null restriction, you need to modify the running class.
One thing that you could do is use apt to extract information about annotated parameters, then use a tool like aspectj to modify those classes at runtime to check the parameter value.
But that's a topic that's way too broad for a single SO question.
#Nullable, #Nonnull are locating in package: javax.annotation
Checkout guava, its got some nice things are type safety:
http://code.google.com/p/guava-libraries/wiki/GuavaExplained

Categories