of 21 /21
LO @JAVA @WORKSHOP @2015 @CSCO @GSI @B @AT @JDK @JRE @J2EE @ECLIPSE @SUNONE SAMPLE @NETBEANS @LURCHI @ASL @LXI @P @NONNULL @NOSKILL @RASPBERRY @ARDUINO @INTERFACE @JAVA @RULEZ @NOT @CLASS @ JAVA @ANNOTATIONS @EVERYWHERE @JAV FAIR @GSI @UNILAC @SIS @ESR @FLAI LSA10 @PYTHON @IOT @JSON @TOI @B @BUZZWORDS @HASHTAG @WIFI @RJ45 @IMPORT @GLADOS @INCLUDE @USING @NOT42 @SUPERUSER @NOPWD @SYSDEV @JAVANOOB @NOIDEA @CONFUSION @NE LOBI @PRESENTER @RAINER @HASEITL

ANNOTATIONS @EVERYWHERE @JAVA @FAIR @GSI ... - … fileJava Workshop 2015 - Annotations Everywhere - Rainer Haseitl CHECKER FRAMEWORK 8 Annotations in the checker framework! @NonNull

Embed Size (px)

Citation preview

@HLO @JAVA @WORKSHOP @2015 @CSCO @GSI @BEL @AT @JDK @JRE @J2EE @ECLIPSE @SUNONE

ESAMPLE @NETBEANS @LURCHI @ASL @LXI @PPM @NONNULL @NOSKILL @RASPBERRY @ARDUINO @INTERFACE @JAVA @RULEZ @NOT @CLASS @

@JAVA @ANNOTATIONS @EVERYWHERE @JAVA @FAIR @GSI @UNILAC @SIS @ESR @FLAIR @LSA10 @PYTHON @IOT @JSON @TOI @BU @BUZZWORDS @HASHTAG @WIFI @RJ45 @IMPORT @GLADOS @INCLUDE @USING @NOT42 @SUPERUSER @NOPWD @SYSDEV @JAVANOOB @NOIDEA @CONFUSION @NE

@LOBI @PRESENTER @RAINER @HASEITL @

Java Workshop 2015 - Annotations Everywhere - Rainer Haseitl

ANNOTATIONS?

2

since JDK 5.0: annotations for definitions @Deprecated, @Override, @SuppressWarnings, … !Spring Framework: @Transactional @Cacheable("clientCache") !JDK 8: annotations wherever a type is used („Type Annotations“) @NonNull @Readonly @YourOwnAnnotation

Java Workshop 2015 - Annotations Everywhere - Rainer Haseitl

EXAMPLE

3

import org.checkerframework.checker.nullness.qual.*;!public class GetStarted { public static void main(String[] args) { @NonNull Object ref = new Object(); }}

using Checker Framework by University of Washington

Annotation can be written for Java < 1.8 as /*@NonNull*/ Object ref = new Object();

Java Workshop 2015 - Annotations Everywhere - Rainer Haseitl

EXAMPLE

4

import org.checkerframework.checker.nullness.qual.*;!public class GetStarted { public static void main(String[] args) { @NonNull Object ref = new Object(); // ... some code ... ref = null; }}

using Checker Framework by University of Washington

Checker reports: (…) incompatible types in assignment (…)

Java Workshop 2015 - Annotations Everywhere - Rainer Haseitl

EXAMPLE

5

public class GetStarted { public static void main(String[] args) { @NonNull Object ref = new Object(); Map<String, Object> myMap = new HashMap<>(); ref = myMap.get(„key"); // returns null if „key“ not found }}

using Checker Framework by University of Washington

Java Workshop 2015 - Annotations Everywhere - Rainer Haseitl

EXAMPLE

6

public class GetStarted { public static void main(String[] args) { @NonNull Object ref = new Object(); Map<String, Object> myMap = new HashMap<>(); ref = myMap.get(„key"); // returns null if „key“ not found }}

using Checker Framework by University of Washington

Checker reports: incompatible types in assignment. ref = myMap.get("key"); found : @Initialized @Nullable Object required: @UnknownInitialization @NonNull Object

Java Workshop 2015 - Annotations Everywhere - Rainer Haseitl

ANNOTATION PLACING

7

Return value: ! @Interned String intern() { ... } !!Parameter: ! int compareTo(@NonNull String other) { ... }!!receiver ("this" parameter) ! String toString(@ReadOnly MyClass this) { ... }!!generics: non-null list of interned Strings ! @NonNull List<@Interned String> messages;!!arrays: non-null array of interned Strings ! @Interned String @NonNull [] messages;!!cast ! myDate = (@ReadOnly Date) readonlyObject;

Java Workshop 2015 - Annotations Everywhere - Rainer Haseitl

CHECKER FRAMEWORK

8

Annotations in the checker framework @NonNull (never null) @Nullable (can be null) @Regex @Interned @GuardedBy (Concurrency stuff) @Tainted (indicate possibly malicious user input) Units - @s, @m, @g, @A, @K, @mol, @cd !and other fancy checkers: http://types.cs.washington.edu/checker-framework/current/checker-framework-manual.html !!available as Command Line / Eclipse Plugin / NetBeans

Integer x = new Integer(22); Integer y = new Integer(22); System.out.println(x == y); // prints false!

Java Workshop 2015 - Annotations Everywhere - Rainer Haseitl

OWN ANNOTATIONS

9

Example: @Localizable

public @interface Localizable{}

Localizable.java

@Localizablepublic class JavaAnnotations{ public static void main(String[] args) { }}

JavaAnnotations.java

Java Workshop 2015 - Annotations Everywhere - Rainer Haseitl

OWN ANNOTATIONS

10

Example: @Localizable

@Localizablepublic class JavaAnnotations{ public static void main(String[] args) { System.out.println("Localizable: " + JavaAnnotations.class.isAnnotationPresent(Localizable.class)); }}

JavaAnnotations.java

Java Workshop 2015 - Annotations Everywhere - Rainer Haseitl

OWN ANNOTATIONS

11

Example: @Localizable

@Localizablepublic class JavaAnnotations{ public static void main(String[] args) { System.out.println("Localizable: " + JavaAnnotations.class.isAnnotationPresent(Localizable.class)); }}

JavaAnnotations.java

>>> Localizable: false

Java Workshop 2015 - Annotations Everywhere - Rainer Haseitl

OWN ANNOTATIONS

12

Example: @Localizable

import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;!@Retention(RetentionPolicy.RUNTIME)public @interface Localizable{}

Localizable.java

Source: Annotations are discarded by the compiler Class: Annotations are in class file but not kept for VM (default) Runtime: VM can read the annotations

Java Workshop 2015 - Annotations Everywhere - Rainer Haseitl

OWN ANNOTATIONS

13

Encryption example (by checker framework)public void sendPassword() { String password = getUserPassword(); sendOverInternet(password);}!// Only send encrypted data!public void sendOverInternet(@Encrypted String msg) { // ...}!private String getUserPassword() { return "!@#$Really Good Password**";}

Java Workshop 2015 - Annotations Everywhere - Rainer Haseitl

OWN ANNOTATIONS

14

Encryption example (by checker framework)public void sendPassword() { String password = getUserPassword(); sendOverInternet(password);}!// Only send encrypted data!public void sendOverInternet(@Encrypted String msg) { // ...}!private String getUserPassword() { return "!@#$Really Good Password**";}

!incompatible types in argument. sendOverInternet(password); found : @PossibleUnencrypted String required: @Encrypted String EncryptionDemo.java /encryption-checker/src/encrypted line 34 Checker Framework Problem

Java Workshop 2015 - Annotations Everywhere - Rainer Haseitl

OWN ANNOTATIONS

15

Encryption example (by checker framework)public void sendPassword() { String password = getUserPassword(); // sendOverInternet(password); sendOverInternet(encrypt(password));}!// Only send encrypted data!public void sendOverInternet(@Encrypted String msg) { // ...}!public @Encrypted String encrypt(String text) { @Encrypted String encryptedText = new @Encrypted String(); // ... encryption magic return encryptedText;}

Java Workshop 2015 - Annotations Everywhere - Rainer Haseitl

ATTRIBUTES

16

OpenBook annotation example with attributes

public @interface ListOfFilesResource{ String value();}

ListOfFileResources.java

@ListOfFilesResource( value = "/home/" ) public String[] files;

Usage:

(…)if ( field.isAnnotationPresent( ListOfFilesResource.class ) ) field.set( newInstance, new File(field.getAnnotation(ListOfFilesResource.class ).value().toString()).list() );)(…)

ResourceReader.java (custom class to fill the attributes):

not a return value but type of the attribute

/home/

Java Workshop 2015 - Annotations Everywhere - Rainer Haseitl

ADVANCED USAGE

17

OpenBook annotation example with attributes

@Documented@Target( ElementType.FIELD )@Retention( RetentionPolicy.RUNTIME )!public @interface UrlResource{ enum UpperLowerCase { UNCHANGED, LOWERCASE, UPPERCASE }! String value();! boolean trim() default false;! UpperLowerCase upperLowerCase() default UpperLowerCase.UNCHANGED;! Class<? extends ResourceConverter>[] converter() default { };}

UrlResource.java

Java Workshop 2015 - Annotations Everywhere - Rainer Haseitl

ADVANCED USAGE

18

OpenBook annotation example with attributes

@Documented@Target( ElementType.FIELD )@Retention( RetentionPolicy.RUNTIME )!public @interface UrlResource{ enum UpperLowerCase { UNCHANGED, LOWERCASE, UPPERCASE }! String value();! boolean trim() default false;! UpperLowerCase upperLowerCase() default UpperLowerCase.UNCHANGED;! Class<? extends ResourceConverter>[] converter() default { };}

UrlResource.java

annotation will show up in the documentation annotation usage is allowed for

static and object variables („FIELD“)

enum definitions are allowed

optional default values

array of subclasses of „ResourceConverter“

Java Workshop 2015 - Annotations Everywhere - Rainer Haseitl

ADVANCED USAGE

19

OpenBook annotation example with attributes

public @interface UrlResource{ enum UpperLowerCase { UNCHANGED, LOWERCASE, UPPERCASE } String value(); boolean trim() default false; UpperLowerCase upperLowerCase() default UpperLowerCase.UNCHANGED; Class<? extends ResourceConverter>[] converter() default { };}

UrlResource.java

@UrlResource( value = "http://url.tld/someTextFile.txt", converter = { RemoveNoWordCharactersConverter.class, SortConverter.class } ) public String testFile;

Usage:

Java Workshop 2015 - Annotations Everywhere - Rainer Haseitl

FURTHER READING

20

Project Lombok - http://projectlombok.org/ Automatic generation of Getters/Setters/Copy constructor/…

Java Workshop 2015 - Annotations Everywhere - Rainer Haseitl

REFERENCES

21

Quick overview what’s new with annotations https://blogs.oracle.com/java-platform-group/entry/java_8_s_new_type !Checker Framework & Examples http://types.cs.washington.edu/checker-framework/ !Retention http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/RetentionPolicy.html !Annotation Examples http://openbook.rheinwerk-verlag.de/javainsel9/javainsel_25_006.htm

@NoQuestions?!@kthxbye