SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Java 8 Type Annotations:
Tools and Opportunities
Todd Schiller | FinLingua
March 24, 2014
Copyright ©2014 FinLingua, Inc. 1
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 data
List<@NonNull String> strings
MyGraph = (@Immutable Graph) tmpGraph;
Copyright ©2014 FinLingua, Inc. 2
Annotations are just syntax,
tools give them their semantics (meaning)
Complementary Goals:
1. Error Checking: quality
2. Metaprogramming: productivity
Copyright ©2014 FinLingua, Inc. 3
Java 7: Overrides
@Override
protected boolean displaySensitiveInfo()
...
}
Problem: dynamic dispatch is tricky
Solution: have a tool (the compiler) check
inheritance automatically
Copyright ©2014 FinLingua, Inc. 4
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
Copyright ©2014 FinLingua, Inc. 5
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
Copyright ©2014 FinLingua, Inc. 6
Talk Outline
1. Type Annotation Syntax
2. Error Checking
3. Metaprogramming
Copyright ©2014 FinLingua, Inc. 7
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> {}
Copyright ©2014 FinLingua, Inc. 8
Type Annotations are Stored in the
Class File
• Can be accessed via reflection
• Local variable annotations are stored, too
• Backward-compatible with Java 7
Copyright ©2014 FinLingua, Inc. 9
Type Annotations Don’t Affect Execution
File file = ...;
@Encrypted File encryptedFile = ...;
// These lines call the same method
connection.Send(file);
connection.Send(encryptedFile);
Copyright ©2014 FinLingua, Inc. 10
class Connection{
// Impossible:
void send(@Encrypted File file) { ... }
void send( File file) { ... }
...
}
Copyright ©2014 FinLingua, Inc. 11
Type Annotations Don’t Affect Execution
Receiver Annotations
Receiver
@Open MyFile file = ...;
... = file.read();
class MyFile {
Byte[] read() { ... }
...
}
Where is the type
of this?
Copyright ©2014 FinLingua, Inc. 12
Receiver Annotations
Receiver
@Open MyFile file = ...;
... = file.read();
class MyFile {
Byte[] read(@Open MyFile this) { ... }
...
} New in Java 8
Copyright ©2014 FinLingua, Inc. 13
Type Annotations Don’t Affect
Execution
// This code will compile, run, (and crash)!
@Closed MyFile file = ...;
... = file.read();
Copyright ©2014 FinLingua, Inc. 14
Talk Outline
1. Type Annotation Syntax
2. Error Checking
3. Metaprogramming
Copyright ©2014 FinLingua, Inc. 15
Run-time Type Checking
Use Aspect Oriented Programming (AOP) to
insert run-time checks
Byte[] 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
Copyright ©2014 FinLingua, Inc. 16
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!
Copyright ©2014 FinLingua, Inc. 17
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
Copyright ©2014 FinLingua, Inc. 18
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
Copyright ©2014 FinLingua, Inc. 19
Type Checking via Subtyping
@MaybeTainted
@Untainted
userInput = dbQuery; // Safe
dbQuery = "SELECT * FROM " + userInput; // Invalid!
@MaybeTainted String userInput;
@Untainted String dbQuery;
Copyright ©2014 FinLingua, Inc. 20
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
Copyright ©2014 FinLingua, Inc. 21
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
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
Copyright ©2014 FinLingua, Inc. 23
Type System Brainstorming
1. Runtime Behavior to Prevent
2. Legal Operations
3. Types of Data
Copyright ©2014 FinLingua, Inc. 24
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
Copyright ©2014 FinLingua, Inc. 25
Error-Checking with Type Annotations
Support
Checker Framework Full support, including annotations in comments
Eclipse Null error analysis support
IntelliJ IDEA Can write custom inspectors, no null error
analysis support
No Support
PMD
Coverity
Find Bugs No Java 8 support
Check Style No Java 8 support
Copyright ©2014 FinLingua, Inc. 26
Talk Outline
1. Type Annotation Syntax
2. Error Checking
3. Metaprogramming
Copyright ©2014 FinLingua, Inc. 27
Metaprogramming
Aspect Oriented Programming
• AspectJ: @Aspect, @Pointcut
Dependency Injection
• Spring: @Autowired, @Required
• Guice: @Inject
Persistence
• Hibernate/JPA: @Entity
Copyright ©2014 FinLingua, Inc. 28
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;
Copyright ©2014 FinLingua, Inc. 29
Fine-Grained Aspect Oriented
Programming
Annotations on local variables:
Copyright ©2014 FinLingua, Inc. 30
// Trace all calls made to the ar object
@Trace AuthorizationRequest ar = ...
Refine Join-Points:
void showSecrets(@Authenticated User user);
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
Copyright ©2014 FinLingua, Inc. 31
Java 8: Annotations on any Uses of
Types
Annotations are just syntax,
tools give them their semantics (meaning)
Complementary Goals:
1. Error Checking: quality
2. Metaprogramming: productivity
Copyright ©2014 FinLingua, Inc. 32
References
• The Checker Framework: http://checkerframework.org/
• MCO trajectory:
ftp://ftp.hq.nasa.gov/pub/pao/reports/1999/MCO_report.pdf
• Werner Dietl et al. Building and using pluggable type-
checkers. 2011.
• Marc Eaddy and Alfred Aho. Statement Annotations for Fine-
Grained Advising. 2006.
• Adrian Sampson et al. EnerJ: Approximate Data Types for Safe
and General Low-Power Computation. 2011.
Copyright ©2014 FinLingua, Inc. 33

Weitere ähnliche Inhalte

Was ist angesagt?

Bt0074 oops with java
Bt0074 oops with javaBt0074 oops with java
Bt0074 oops with javaTechglyphs
 
Java Code Generation for Productivity
Java Code Generation for ProductivityJava Code Generation for Productivity
Java Code Generation for ProductivityDavid Noble
 
Java se 8 fundamentals
Java se 8 fundamentalsJava se 8 fundamentals
Java se 8 fundamentalsmegharajk
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For SyntaxPravinYalameli
 
Qb it1301
Qb   it1301Qb   it1301
Qb it1301ArthyR3
 
Introduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging APIIntroduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging APIwhite paper
 
Java annotations
Java annotationsJava annotations
Java annotationsSujit Kumar
 
Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview QuestionsKuntal Bhowmick
 
Defaultification Refactoring: A Tool for Automatically Converting Java Method...
Defaultification Refactoring: A Tool for Automatically Converting Java Method...Defaultification Refactoring: A Tool for Automatically Converting Java Method...
Defaultification Refactoring: A Tool for Automatically Converting Java Method...Raffi Khatchadourian
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using ReflectionGanesh Samarthyam
 

Was ist angesagt? (20)

Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java basic
Java basicJava basic
Java basic
 
Bt0074 oops with java
Bt0074 oops with javaBt0074 oops with java
Bt0074 oops with java
 
Java platform
Java platformJava platform
Java platform
 
Java Code Generation for Productivity
Java Code Generation for ProductivityJava Code Generation for Productivity
Java Code Generation for Productivity
 
The Seven Pillars Of Asp.Net
The Seven Pillars Of Asp.NetThe Seven Pillars Of Asp.Net
The Seven Pillars Of Asp.Net
 
Java features
Java featuresJava features
Java features
 
Core java
Core javaCore java
Core java
 
Java se 8 fundamentals
Java se 8 fundamentalsJava se 8 fundamentals
Java se 8 fundamentals
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Qb it1301
Qb   it1301Qb   it1301
Qb it1301
 
Unit 5 Java
Unit 5 JavaUnit 5 Java
Unit 5 Java
 
Introduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging APIIntroduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging API
 
Java annotations
Java annotationsJava annotations
Java annotations
 
Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview Questions
 
Defaultification Refactoring: A Tool for Automatically Converting Java Method...
Defaultification Refactoring: A Tool for Automatically Converting Java Method...Defaultification Refactoring: A Tool for Automatically Converting Java Method...
Defaultification Refactoring: A Tool for Automatically Converting Java Method...
 
Annotations
AnnotationsAnnotations
Annotations
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
 

Andere mochten auch

Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»
Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»
Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»Anna Shymchenko
 
Trends and future of java
Trends and future of javaTrends and future of java
Trends and future of javaCsaba Toth
 
Java World, Java Trends, Java 8 and Beyond (iForum - 2014)
Java World, Java Trends, Java 8 and Beyond (iForum - 2014)Java World, Java Trends, Java 8 and Beyond (iForum - 2014)
Java World, Java Trends, Java 8 and Beyond (iForum - 2014)Olena Syrota
 
Hacking Java - Enhancing Java Code at Build or Runtime
Hacking Java - Enhancing Java Code at Build or RuntimeHacking Java - Enhancing Java Code at Build or Runtime
Hacking Java - Enhancing Java Code at Build or RuntimeSean P. Floyd
 
A Java Implementer's Guide to Boosting Apache Spark Performance by Tim Ellison.
A Java Implementer's Guide to Boosting Apache Spark Performance by Tim Ellison.A Java Implementer's Guide to Boosting Apache Spark Performance by Tim Ellison.
A Java Implementer's Guide to Boosting Apache Spark Performance by Tim Ellison.J On The Beach
 
Anatomy of Spark SQL Catalyst - Part 2
Anatomy of Spark SQL Catalyst - Part 2Anatomy of Spark SQL Catalyst - Part 2
Anatomy of Spark SQL Catalyst - Part 2datamantra
 
Anatomy of spark catalyst
Anatomy of spark catalystAnatomy of spark catalyst
Anatomy of spark catalystdatamantra
 
Ingesting Drone Data into Big Data Platforms
Ingesting Drone Data into Big Data Platforms Ingesting Drone Data into Big Data Platforms
Ingesting Drone Data into Big Data Platforms Timothy Spann
 
Conférence sur les annotations Java par Olivier Croisier (Zenika) au Paris JUG
Conférence sur les annotations Java par Olivier Croisier (Zenika) au Paris JUGConférence sur les annotations Java par Olivier Croisier (Zenika) au Paris JUG
Conférence sur les annotations Java par Olivier Croisier (Zenika) au Paris JUGZenika
 

Andere mochten auch (11)

Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»
Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»
Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»
 
Trends and future of java
Trends and future of javaTrends and future of java
Trends and future of java
 
Java World, Java Trends, Java 8 and Beyond (iForum - 2014)
Java World, Java Trends, Java 8 and Beyond (iForum - 2014)Java World, Java Trends, Java 8 and Beyond (iForum - 2014)
Java World, Java Trends, Java 8 and Beyond (iForum - 2014)
 
Java annotation
Java annotationJava annotation
Java annotation
 
Hacking Java - Enhancing Java Code at Build or Runtime
Hacking Java - Enhancing Java Code at Build or RuntimeHacking Java - Enhancing Java Code at Build or Runtime
Hacking Java - Enhancing Java Code at Build or Runtime
 
A Java Implementer's Guide to Boosting Apache Spark Performance by Tim Ellison.
A Java Implementer's Guide to Boosting Apache Spark Performance by Tim Ellison.A Java Implementer's Guide to Boosting Apache Spark Performance by Tim Ellison.
A Java Implementer's Guide to Boosting Apache Spark Performance by Tim Ellison.
 
Anatomy of Spark SQL Catalyst - Part 2
Anatomy of Spark SQL Catalyst - Part 2Anatomy of Spark SQL Catalyst - Part 2
Anatomy of Spark SQL Catalyst - Part 2
 
Anatomy of spark catalyst
Anatomy of spark catalystAnatomy of spark catalyst
Anatomy of spark catalyst
 
Ingesting Drone Data into Big Data Platforms
Ingesting Drone Data into Big Data Platforms Ingesting Drone Data into Big Data Platforms
Ingesting Drone Data into Big Data Platforms
 
Annotations in Java
Annotations in JavaAnnotations in Java
Annotations in Java
 
Conférence sur les annotations Java par Olivier Croisier (Zenika) au Paris JUG
Conférence sur les annotations Java par Olivier Croisier (Zenika) au Paris JUGConférence sur les annotations Java par Olivier Croisier (Zenika) au Paris JUG
Conférence sur les annotations Java par Olivier Croisier (Zenika) au Paris JUG
 

Ähnlich wie Type Annotations in Java 8

Developer Friendly API Design
Developer Friendly API DesignDeveloper Friendly API Design
Developer Friendly API Designtheamiableapi
 
Introduction to Core Java Programming
Introduction to Core Java ProgrammingIntroduction to Core Java Programming
Introduction to Core Java ProgrammingRaveendra R
 
Spring training
Spring trainingSpring training
Spring trainingTechFerry
 
PhpStorm: Symfony2 Plugin
PhpStorm: Symfony2 PluginPhpStorm: Symfony2 Plugin
PhpStorm: Symfony2 PluginHaehnchen
 
Build, logging, and unit test tools
Build, logging, and unit test toolsBuild, logging, and unit test tools
Build, logging, and unit test toolsAllan Huang
 
Introduction to Dynamic Analysis of Android Application
Introduction to Dynamic Analysis of Android ApplicationIntroduction to Dynamic Analysis of Android Application
Introduction to Dynamic Analysis of Android ApplicationKelwin Yang
 
JavaOne 2015: From Java Code to Machine Code
JavaOne 2015: From Java Code to Machine CodeJavaOne 2015: From Java Code to Machine Code
JavaOne 2015: From Java Code to Machine CodeChris Bailey
 
2022 APIsecure_Securing APIs with Open Standards
2022 APIsecure_Securing APIs with Open Standards2022 APIsecure_Securing APIs with Open Standards
2022 APIsecure_Securing APIs with Open StandardsAPIsecure_ Official
 
Introduction to Software Development
Introduction to Software DevelopmentIntroduction to Software Development
Introduction to Software DevelopmentZeeshan MIrza
 
Unit Tests? It is Very Simple and Easy!
Unit Tests? It is Very Simple and Easy!Unit Tests? It is Very Simple and Easy!
Unit Tests? It is Very Simple and Easy!Return on Intelligence
 
Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Oliver Gierke
 
Scala for Test Automation
Scala for Test AutomationScala for Test Automation
Scala for Test Automationrthanavarapu
 
Fernando Arnaboldi - Exposing Hidden Exploitable Behaviors Using Extended Dif...
Fernando Arnaboldi - Exposing Hidden Exploitable Behaviors Using Extended Dif...Fernando Arnaboldi - Exposing Hidden Exploitable Behaviors Using Extended Dif...
Fernando Arnaboldi - Exposing Hidden Exploitable Behaviors Using Extended Dif...Codemotion
 
Utilisation des capteurs dans les applications windows 8
Utilisation des capteurs dans les applications windows 8Utilisation des capteurs dans les applications windows 8
Utilisation des capteurs dans les applications windows 8Intel Developer Zone Community
 
solution Challenge design and flutter day.pptx
solution Challenge design and flutter day.pptxsolution Challenge design and flutter day.pptx
solution Challenge design and flutter day.pptxGoogleDeveloperStude22
 
Bypass Security Checking with Frida
Bypass Security Checking with FridaBypass Security Checking with Frida
Bypass Security Checking with FridaSatria Ady Pradana
 
Review Paper on Online Java Compiler
Review Paper on Online Java CompilerReview Paper on Online Java Compiler
Review Paper on Online Java CompilerIRJET Journal
 
OpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConOpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConos890
 

Ähnlich wie Type Annotations in Java 8 (20)

Developer Friendly API Design
Developer Friendly API DesignDeveloper Friendly API Design
Developer Friendly API Design
 
Introduction to Core Java Programming
Introduction to Core Java ProgrammingIntroduction to Core Java Programming
Introduction to Core Java Programming
 
Spring training
Spring trainingSpring training
Spring training
 
PhpStorm: Symfony2 Plugin
PhpStorm: Symfony2 PluginPhpStorm: Symfony2 Plugin
PhpStorm: Symfony2 Plugin
 
Spring boot
Spring bootSpring boot
Spring boot
 
Build, logging, and unit test tools
Build, logging, and unit test toolsBuild, logging, and unit test tools
Build, logging, and unit test tools
 
Introduction to Dynamic Analysis of Android Application
Introduction to Dynamic Analysis of Android ApplicationIntroduction to Dynamic Analysis of Android Application
Introduction to Dynamic Analysis of Android Application
 
JavaOne 2015: From Java Code to Machine Code
JavaOne 2015: From Java Code to Machine CodeJavaOne 2015: From Java Code to Machine Code
JavaOne 2015: From Java Code to Machine Code
 
Core java
Core javaCore java
Core java
 
2022 APIsecure_Securing APIs with Open Standards
2022 APIsecure_Securing APIs with Open Standards2022 APIsecure_Securing APIs with Open Standards
2022 APIsecure_Securing APIs with Open Standards
 
Introduction to Software Development
Introduction to Software DevelopmentIntroduction to Software Development
Introduction to Software Development
 
Unit Tests? It is Very Simple and Easy!
Unit Tests? It is Very Simple and Easy!Unit Tests? It is Very Simple and Easy!
Unit Tests? It is Very Simple and Easy!
 
Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?
 
Scala for Test Automation
Scala for Test AutomationScala for Test Automation
Scala for Test Automation
 
Fernando Arnaboldi - Exposing Hidden Exploitable Behaviors Using Extended Dif...
Fernando Arnaboldi - Exposing Hidden Exploitable Behaviors Using Extended Dif...Fernando Arnaboldi - Exposing Hidden Exploitable Behaviors Using Extended Dif...
Fernando Arnaboldi - Exposing Hidden Exploitable Behaviors Using Extended Dif...
 
Utilisation des capteurs dans les applications windows 8
Utilisation des capteurs dans les applications windows 8Utilisation des capteurs dans les applications windows 8
Utilisation des capteurs dans les applications windows 8
 
solution Challenge design and flutter day.pptx
solution Challenge design and flutter day.pptxsolution Challenge design and flutter day.pptx
solution Challenge design and flutter day.pptx
 
Bypass Security Checking with Frida
Bypass Security Checking with FridaBypass Security Checking with Frida
Bypass Security Checking with Frida
 
Review Paper on Online Java Compiler
Review Paper on Online Java CompilerReview Paper on Online Java Compiler
Review Paper on Online Java Compiler
 
OpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConOpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheCon
 

Kürzlich hochgeladen

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 

Kürzlich hochgeladen (20)

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 

Type Annotations in Java 8

  • 1. Java 8 Type Annotations: Tools and Opportunities Todd Schiller | FinLingua March 24, 2014 Copyright ©2014 FinLingua, Inc. 1
  • 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 data List<@NonNull String> strings MyGraph = (@Immutable Graph) tmpGraph; Copyright ©2014 FinLingua, Inc. 2
  • 3. Annotations are just syntax, tools give them their semantics (meaning) Complementary Goals: 1. Error Checking: quality 2. Metaprogramming: productivity Copyright ©2014 FinLingua, Inc. 3
  • 4. Java 7: Overrides @Override protected boolean displaySensitiveInfo() ... } Problem: dynamic dispatch is tricky Solution: have a tool (the compiler) check inheritance automatically Copyright ©2014 FinLingua, Inc. 4
  • 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 Copyright ©2014 FinLingua, Inc. 5
  • 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 Copyright ©2014 FinLingua, Inc. 6
  • 7. Talk Outline 1. Type Annotation Syntax 2. Error Checking 3. Metaprogramming Copyright ©2014 FinLingua, Inc. 7
  • 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> {} Copyright ©2014 FinLingua, Inc. 8
  • 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 Copyright ©2014 FinLingua, Inc. 9
  • 10. Type Annotations Don’t Affect Execution File file = ...; @Encrypted File encryptedFile = ...; // These lines call the same method connection.Send(file); connection.Send(encryptedFile); Copyright ©2014 FinLingua, Inc. 10
  • 11. class Connection{ // Impossible: void send(@Encrypted File file) { ... } void send( File file) { ... } ... } Copyright ©2014 FinLingua, Inc. 11 Type Annotations Don’t Affect Execution
  • 12. Receiver Annotations Receiver @Open MyFile file = ...; ... = file.read(); class MyFile { Byte[] read() { ... } ... } Where is the type of this? Copyright ©2014 FinLingua, Inc. 12
  • 13. Receiver Annotations Receiver @Open MyFile file = ...; ... = file.read(); class MyFile { Byte[] read(@Open MyFile this) { ... } ... } New in Java 8 Copyright ©2014 FinLingua, Inc. 13
  • 14. Type Annotations Don’t Affect Execution // This code will compile, run, (and crash)! @Closed MyFile file = ...; ... = file.read(); Copyright ©2014 FinLingua, Inc. 14
  • 15. Talk Outline 1. Type Annotation Syntax 2. Error Checking 3. Metaprogramming Copyright ©2014 FinLingua, Inc. 15
  • 16. Run-time Type Checking Use Aspect Oriented Programming (AOP) to insert run-time checks Byte[] 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 Copyright ©2014 FinLingua, Inc. 16
  • 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! Copyright ©2014 FinLingua, Inc. 17
  • 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 Copyright ©2014 FinLingua, Inc. 18
  • 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 Copyright ©2014 FinLingua, Inc. 19
  • 20. Type Checking via Subtyping @MaybeTainted @Untainted userInput = dbQuery; // Safe dbQuery = "SELECT * FROM " + userInput; // Invalid! @MaybeTainted String userInput; @Untainted String dbQuery; Copyright ©2014 FinLingua, Inc. 20
  • 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 Copyright ©2014 FinLingua, Inc. 21
  • 22. 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
  • 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 Copyright ©2014 FinLingua, Inc. 23
  • 24. Type System Brainstorming 1. Runtime Behavior to Prevent 2. Legal Operations 3. Types of Data Copyright ©2014 FinLingua, Inc. 24
  • 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 Copyright ©2014 FinLingua, Inc. 25
  • 26. Error-Checking with Type Annotations Support Checker Framework Full support, including annotations in comments Eclipse Null error analysis support IntelliJ IDEA Can write custom inspectors, no null error analysis support No Support PMD Coverity Find Bugs No Java 8 support Check Style No Java 8 support Copyright ©2014 FinLingua, Inc. 26
  • 27. Talk Outline 1. Type Annotation Syntax 2. Error Checking 3. Metaprogramming Copyright ©2014 FinLingua, Inc. 27
  • 28. Metaprogramming Aspect Oriented Programming • AspectJ: @Aspect, @Pointcut Dependency Injection • Spring: @Autowired, @Required • Guice: @Inject Persistence • Hibernate/JPA: @Entity Copyright ©2014 FinLingua, Inc. 28
  • 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; Copyright ©2014 FinLingua, Inc. 29
  • 30. Fine-Grained Aspect Oriented Programming Annotations on local variables: Copyright ©2014 FinLingua, Inc. 30 // Trace all calls made to the ar object @Trace AuthorizationRequest ar = ... Refine Join-Points: void showSecrets(@Authenticated User user);
  • 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 Copyright ©2014 FinLingua, Inc. 31
  • 32. Java 8: Annotations on any Uses of Types Annotations are just syntax, tools give them their semantics (meaning) Complementary Goals: 1. Error Checking: quality 2. Metaprogramming: productivity Copyright ©2014 FinLingua, Inc. 32
  • 33. References • The Checker Framework: http://checkerframework.org/ • MCO trajectory: ftp://ftp.hq.nasa.gov/pub/pao/reports/1999/MCO_report.pdf • Werner Dietl et al. Building and using pluggable type- checkers. 2011. • Marc Eaddy and Alfred Aho. Statement Annotations for Fine- Grained Advising. 2006. • Adrian Sampson et al. EnerJ: Approximate Data Types for Safe and General Low-Power Computation. 2011. Copyright ©2014 FinLingua, Inc. 33

Hinweis der Redaktion

  1. The receiver syntax is optional. It does not affect semantics as is useful only for writing type annotations.
  2. Type annotations can be independent from types. For example, @NonNull and @Nullable can be applied to any Object.
  3. The intuition is that the supertype is a superset of the values represented by the subtype.
  4. Comment are for backwards compatibility. You can use the Checker Framework even if you have not adopted Java 8.http://checkerframework.org