type annotations in java 8

33
Java 8 Type Annotations: Tools and Opportunities Todd Schiller | FinLingua March 24, 2014 Copyright ©2014 FinLingua, Inc. 1

Upload: finlingua-inc

Post on 10-May-2015

1.021 views

Category:

Technology


0 download

DESCRIPTION

Java 8 introduces new type annotation syntax (JSR 308) permitting annotations to appear on any use of a type. Type annotations provide exciting new opportunities for tooling such as detecting additional classes of errors at compile-time. This presentation provides an overview of the new type annotation syntax, tools for leveraging type annotations, and type annotation design patterns. These slides are from Todd Schiller's talk at the March 24th New York City Java Meetup.

TRANSCRIPT

Page 1: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 1

Java 8 Type Annotations:Tools and Opportunities

Todd Schiller | FinLinguaMarch 24, 2014

Page 2: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 2

Java 7: annotations on declarations

@Override public boolean equals(Object obj)@Entity class MyPojo implements Serializable

Java 8: annotations on any uses of types

@Encrypted String dataList<@NonNull String> stringsMyGraph = (@Immutable Graph) tmpGraph;

Page 3: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 3

Annotations are just syntax, tools give them their semantics (meaning)

Complementary Goals:1. Error Checking: quality2. Metaprogramming: productivity

Page 4: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 4

Java 7: Overrides

@Override protected boolean displaySensitiveInfo()

...}

Problem: dynamic dispatch is tricky

Solution: have a tool (the compiler) check inheritance automatically

Page 5: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 5

Java 7: Persistence

@Entity@Table(name="tbl_flight")public class Flight implements Serializable { @Id public Long getId() { return id; } ...}

Problem: DB mappings are redundant

Solution: have a tool (e.g., Hibernate) create mappings automatically

Page 6: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 6

Type Information Improves Quality

Mars Climate Orbiter• Unit error in thruster

controller: lbf-s vs. N-s

• Crashed into Mars

• 3 years of work, > $125 million

Page 7: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 7

Talk Outline

1. Type Annotation Syntax

2. Error Checking

3. Metaprogramming

Page 8: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 8

Type Annotations on Any Uses of Types (JSR 308)

@Encrypted String data

List<@NonNull String> strings

MyGraph = (@Immutable Graph) tmpGraph;

class UnmodifiableList<T> implements @ReadOnly List<@ReadOnly T> {}

Page 9: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 9

Type Annotations are Stored in the Class File

• Can be accessed via reflection

• Local variable annotations are stored, too

• Backward-compatible with Java 7

Page 10: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 10

Type Annotations Don’t Affect Execution

File file = ...;@Encrypted File encryptedFile = ...;

// These lines call the same methodconnection.Send(file);connection.Send(encryptedFile);

Page 11: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 11

class Connection{ // Impossible: void send(@Encrypted File file) { ... } void send( File file) { ... } ...}

Type Annotations Don’t Affect Execution

Page 12: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 12

Receiver Annotations

Receiver

@Open MyFile file = ...;... = file.read();

class MyFile {Byte[] read() { ... }...

}

Where is the type of this?

Page 13: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 13

Receiver Annotations

Receiver

@Open MyFile file = ...;... = file.read();

class MyFile {Byte[] read(@Open MyFile this) { ... }...

} New in Java 8

Page 14: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 14

Type Annotations Don’t Affect Execution

// This code will compile, run, (and crash)!@Closed MyFile file = ...;... = file.read();

Page 15: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 15

Talk Outline

1. Type Annotation Syntax

2. Error Checking

3. Metaprogramming

Page 16: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 16

Run-time Type CheckingUse Aspect Oriented Programming (AOP) to insert run-time checksByte[] read(@Open MyFile this){ // Inserted by the AOP tool if (!this.isOpen()){

throw new IllegalArgumentException(...); } ...}

Refined Claim: Type annotations don’t, on their own, affect execution

Page 17: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 17

Static Type Checking

Prevent run-time exceptions at compile-time:

List<String> xs = ...;String x = xs.get(0); // Known to be valid... = x.Trim(); // Method known to exist

int sum = xs.get(1) + 3; // Compiler error... = x.Foo(); // Compiler error

NullPointerException!

Page 18: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 18

Type Annotations Qualify Types

List<@NonNull String> xs = ...;@NonNull String x = xs.get(0); ... = x.Trim(); // OK

Other ways to qualify the String type:

@Encrypted String@Format({FLOAT, INT}) String@Localized String

Page 19: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 19

Type Checking Annotations

Annotations are just syntax, tools give them their semantics (meaning)

Java 8 compiler does not check the annotations

Java provides a Pluggable Annotation Processing API and Java Compiler API

Page 20: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 20

Type Checking via Subtyping

@MaybeTainted

@Untainted

userInput = dbQuery; // SafedbQuery = "SELECT * FROM " + userInput; // Invalid!

@MaybeTainted String userInput;@Untainted String dbQuery;

Page 21: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 21

The Checker Framework: Pluggable Type-Checking

• Many built-in checkers: null pointers, locking, security, string syntax (regex, format strings), internationalization, ...

• Quickly build your own checker

• Uses Java 8 type annotations (or comments)– List<@Nullable String>– List</*@Nullable*/ String>

• http://checkerframework.org

Page 22: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 22

void nullSafe( MyObject nonNullByDefault, @Nullable MyObject mightBeNull

){

// Smart defaults nonNullByDefault.Foo(); // Safe

mightBeNull.Foo(); // Unsafe!

if (mightBeNull != null){ // Flow-sensitive

mightBeNull.Foo(); // Safe }}

Low Annotation Overhead

Page 23: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 23

Our Experience

• Checkers reveal important latent bugs–Ran on >3 million LOC of real-world code– Found hundreds of user-visible bugs

• Mean 2.6 annotations per kLOC

• Quickly build your own checkers

Page 24: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 24

Type System Brainstorming

1. Runtime Behavior to Prevent

2. Legal Operations

3. Types of Data

Page 25: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 25

Type System Brainstorming

1. Runtime Behavior to Prevent Don’t send unencrypted data over the network

2. Legal Operations Only pass encrypted data to send(...)

3. Types of Data Encrypted, Unencrypted

@MaybeEncrypted

@Encrypted

Page 26: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 26

Error-Checking with Type Annotations

SupportChecker Framework Full support, including annotations in comments

Eclipse Null error analysis support

IntelliJ IDEA Can write custom inspectors, no null error analysis support

No SupportPMDCoverityFind Bugs No Java 8 support

Check Style No Java 8 support

Page 27: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 27

Talk Outline

1. Type Annotation Syntax

2. Error Checking

3. Metaprogramming

Page 28: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 28

Metaprogramming

Aspect Oriented Programming• AspectJ: @Aspect, @Pointcut

Dependency Injection• Spring: @Autowired, @Required• Guice: @Inject

Persistence• Hibernate/JPA: @Entity

Page 29: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 29

Fine-Grained Dependency Injection

@Autowired private Store<Product> s1; @Autowired private Store<Service> s2;

Spring 4 considers generics a form of qualifier:

Type Annotations would allow further refinement:

@Autowired private Store<@Prod(Type.Grocery) Product> s1;

Page 30: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 30

Fine-Grained Aspect Oriented Programming

Annotations on local variables:

// Trace all calls made to the ar object @Trace AuthorizationRequest ar = ...

Refine Join-Points:

void showSecrets(@Authenticated User user);

Page 31: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 31

EnerJ: Approximate Computing Model

Specify which data is non-critical:@Approx int pixel

Run-time can approximate that data (e.g., convergence criteria)

Checker ensures approximate data doesn’t flow into precise expressions

Page 32: Type Annotations in Java 8

Copyright ©2014 FinLingua, Inc. 32

Java 8: Annotations on any Uses of Types

Annotations are just syntax, tools give them their semantics (meaning)

Complementary Goals:1. Error Checking: quality2. Metaprogramming: productivity