Skip to content

Instantly share code, notes, and snippets.

@sundararajana
Last active August 29, 2015 14:15
Show Gist options
  • Save sundararajana/c5981a2c0ca638bebb0c to your computer and use it in GitHub Desktop.
Save sundararajana/c5981a2c0ca638bebb0c to your computer and use it in GitHub Desktop.
Annotations on type use - Using #java8 annotations and "checker framework"
import org.checkerframework.checker.nullness.qual.*;
/**
* Before Java SE 8 annotations could only be applied to declarations.
* With Java SE 8+, annotations can also be applied to any type use.
*
* See: http://docs.oracle.com/javase/tutorial/java/annotations/type_annotations.html
*
* To compile this sample:
*
* 1) Download "checker framework" from
* http://types.cs.washington.edu/checker-framework/current/checker-framework.zip
* I used version 1.8.10
*
* 2) Expand check-framework.zip under say $CHECKER_FRAMEWORK directory
*
* 3) $CHECKER_FRAMEWORK/checker/bin/javac -processor NullnessChecker NullCast.java
*
* You should see this warning:
*
<pre>
NullCast.java:35: warning: [cast.unsafe] "@Initialized @Nullable Object" may not be casted to the type "@Initialized @NonNull String"
String s = (@NonNull String)arg;
^
1 warning
</pre>
*
*/
public class NullCast {
public void main(@Nullable Object arg) {
// if you uncomment this null check "if" statement then
// the warning will disappear as the cast is after null check.
// if (arg != null) {
String s = (@NonNull String)arg;
System.out.println(s);
// }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment