SlideShare uma empresa Scribd logo
1 de 61
27 au 29 mars 2013
Java 8, Lambdas, Generics:
How to survive?
Henri Tremblay
Java Champion
tremblay.pro inc.
@henri_tremblay
http://blog.tremblay.pro
NYC Java Meetup Group
Loves
IT Strategy
Performance
Productivity
Great food!
Do Open Source
Henri Tremblay
Try to be useful
September 2004
March 18 2014
Java 7 End of Life
Java 8 support
Lambda
return Tweet.TWEETS.stream()
.collect(Collectors
.partitioningBy(
t->t.containsHashTag("#lambda")));
Lambda = Fun with generics
Stream<Tweet> stream = Tweet.TWEETS.stream();
Predicate<Tweet> lambda = t -> t.containsHashTag("#lambda");
Collector<Tweet, ?, Map<Boolean, List<Tweet>>> collector =
Collectors.partitioningBy(lambda);
return stream.collect(collector);
What do I need to know?
9© OCTO 2011
Why
What do I need to know?
10© OCTO 2011
Why
Covariance
What do I need to know?
11© OCTO 2011
Why
Covariance
Capture
What do I need to know?
12© OCTO 2011
Why
Covariance
Capture
Inference
What do I need to know?
13© OCTO 2011
Why
Covariance
Capture
Inference
Erasure
What do I need to know?
14© OCTO 2011
Why Covariance
Capture Inference
Erasure Bridge
Compiled successfully!
15
Dreaded warnings
16
Type safety: The expression of type List needs
unchecked conversion to conform to List<String>
Type safety: Unchecked cast from
List<capture#1-of ?> to List<String>
Ostrich defense
@SuppressWarnings("unchecked")
17
27 au 29 mars 2013
Why
18© OCTO 2011
Rule #1
A code compiling
without warning should
never ever cause a
ClassCastException
19
27 au 29 mars 2013
Covariance
20
Arrays
Arrays are covariant:
Number n = Integer.MAX_VALUE;
Number[] list = new Integer[0];
Generics are not:
List<Number> l =
new ArrayList<Integer>(); // Illegal
21
Why not?
List<Integer> li = new ArrayList<Integer>();
List<Number> ln = li; // illegal
ln.add(new Float(3.1415));
int i = li.get(0); // ClassCastException
22
Would work if covariant And allow to break rule #1
Why for array?
Integer[] list = // ...
foo(list);
public void foo(Object[] o) {
// ...
}
Arrays and generics don’t mix well
Can’t have an array of generics
List<String>[] lsa = new List<String>[10];// illegal
24
Exception
List<?>[] l = new ArrayList<?>[3];
25
Because
If it was allowed
List<String>[] lsa = new List<String>[10]; // illegal
Object[] oa = lsa; // OK (covariant)
oa[0] = new ArrayList<Integer>(); // OK
oa[0].add(42);
String s = lsa[0].get(0); // bad
26
27 au 29 mars 2013
Capture
27
Capture usually is
Type
List<?> bar();
<T> IExpectationSetters<T> expect(T value);
void andReturn(T value); // Method of IExpectationSetters
expect(bar()).andReturn(new ArrayList<String>());
And you get
The method andReturn(List<capture#6-of ?>) in the type
IExpectationSetters<List<capture#6-of ?>> is not applicable for the arguments
(ArrayList<String>)
28
Detail
List<?> bar();
<T> IExpectationSetters<T> expect(T value);
void andReturn(T value);
expect(bar()).andReturn(new ArrayList<String>());
List<Capture#6> bar = bar();
IExpectationSetters<List<Capture#6>> es =
expect(bar());
es.andReturn(List<Capture#6> value);
29
Only solution
We need to cast
expect((List<String>) bar()).andReturn(new
ArrayList<String>());
But still a warning
Type safety: Unchecked cast from List<capture#6-of ?> to
List<String>
Framework coder tip:
Try to never return a wildcard unless necessary
30
Tell to expect we want a
List<String>
Inference
31
Diamonds are a programmer best friend
List<String> l = new ArrayList<>();
How the compiler tells the type
<T> T anyObject(T clazz)
33
The parameterDetermine
the return
value type
How the compiler tells the type
MyType var = <T> T anyObject()
34
Determine the
return type
The assigned
variable
But watch out with overloading
public void foo(String s)
public void foo(Object o)
foo(anyObject());
35
Can’t
guess the
type
Trick #1
<T> T anyObject(Class<T> clazz)
36
Artificially give the type with a
dedicated parameter
Determine the return
value type
But how to pass a generic?
public void foo(String s)
public void foo(Object o)
foo(anyObject(List<String>.class));
37
Illegal
Some solutions
foo((String) anyObject());
foo((List<String>) anyObject()); // Warning
38
This would work
But still doesn’t work for
generics
Trick #2
So the only solution is
foo(EasyMock.<List<String>> anyObject());
… which sadly doesn’t support static imports
foo(.<List<String>> anyObject()); // Illegal
39
Trick #2 applied to Lambda
return Tweet.TWEETS.stream()
.collect( Collectors.<Tweet, Boolean,
List<Tweet>, Map<Boolean, List<Tweet>>>
groupingBy(t->t.containsHashTag("#lambda"),
HashMap::new, ArrayList::new));
Return type: Map<Boolean, List<Tweet>>
Lambda = Inference
return Tweet.TWEETS.stream()
.collect(Collectors
.partitioningBy(
t->t.containsHashTag("#lambda"));
How did it do it?
Tweet.TWEETS.stream()
List<Tweet> list = Tweet.TWEETS;
Stream<Tweet> stream = list.stream();
How did it do it?
Stream<Tweet> stream = list.stream();
R result = stream.collect(Collector<? super T, ?, R> collector);
R result = stream.collect(Collector<? super Tweet, ?, R> collector);
How did it do it?
stream.collect(Collector<? super Tweet, ?, R> collector);
Collector<T, ?, Map<Boolean, List<T>>> collector =
Collectors.partitioningBy(Predicate<? super T> predicate);
Collector<Tweet, ?, Map<Boolean, List<Tweet>>> collector =
Collectors.partitioningBy(Predicate<? super Tweet> predicate);
How did it do it?
Predicate<? super Tweet> lambda = t -> t.containsHashTag("#lambda");
We now know that
So the best t can be is a Tweet
Predicate<? super Tweet> lambda = (Tweet t) -> t.containsHashTag("#lambda");
Trick #3: Lambda inference
Object o = (Runnable) () -> {
System.out.println("hi");
};
Collections.sort(strings,
(String a, String b) -> a.compareTo(b));
Erasure
47
Erasure…
public void foo() {
List<String> l = new ArrayList<String>();
for (String s : l) {
System.out.println(s);
}
}
No type
public void foo() {
List l = new ArrayList();
for (String s : l) {
System.out.println(s);
}
}
Compilation
… or not erasure
public class A extends ArrayList<String> {}
public static void main(final String[] args) {
ParameterizedType type = (ParameterizedType)
A.class.getGenericSuperclass();
System.out.println(
type.getActualTypeArguments()[0]);
}
 prints class java.lang.String
49
Type class
java.lang.reflect.Type
• GenericArrayType
• ParameterizedType
• TypeVariable
• WildcardType
• Implemented by Class
java.lang.reflect.GenericDeclaration
Implemented by Class, Method, Constructor
50
New powers unleashed!
Useful!
class A {}
abstract class BaseDao<T> {
public T load(final long id) {
// …
}
}
class ADao extends BaseDao<A> {}
51© OCTO 2011
Useful!
@SuppressWarnings("unchecked")
public T load(final long id) {
ParameterizedType type =
(ParameterizedType) getClass()
.getGenericSuperclass();
Type actualType = type.getActualTypeArguments()[0];
return em.find((Class<T>) actualType, (Long) id);
}
ADao
A
BaseDao<A>
Unsafe cast
Bridge
53© OCTO 2011
Everything seems normal…
class A<T> {
abstract void set(T value);
}
class B extends A<String> {
String value;
@Override
void set(final String value) {
this.value = value;
}
}
But is not
class B extends A {
void set(String value) {
this.value = value;
}
volatile void set(Object o){
set((String)o);
}
}
Example
A a = new B();
a.set(new Object());
But at runtime:
java.lang.ClassCastException
Raw type warning Perfectly compiling
The actual problem being
B.class.getDeclaredMethods()
volatile void set(java.lang.Object)
void B.set(java.lang.String)
This
Returns that
And gives you no way to find out
which method is bridged
What about lambdas?
public class A {
public static void main(String[] args) {
Method[] methods = A.class.getDeclaredMethods();
Arrays.stream(methods).forEach(m ->
System.out.println(m + " "
+ m.isBridge() + " " + m.isSynthetic()));
}
}
Prints this
public static void A.main(java.lang.String[]) false false
private static void A.lambda$0(java.lang.reflect.Method) false true
Conclusion
Who has learned
something today?
59© OCTO 2011
Useful links
Nice lambda tutorial (in French):
http://lambda.ninjackaton.ninja-squad.com/
Description of inference types on lambda:
http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-final.html
Everything on generics:
http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html
Hopefully everything on lambdas
http://www.lambdafaq.org/
Conclusion
Questions?
61© OCTO 2011
http://www.montreal-
jug.org/
http://brownbaglunch.fr
@henri_tremblay
http://blog.tremblay.pro
henri@tremblay.pro

Mais conteúdo relacionado

Mais procurados

Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummiesknutmork
 
Refactoring to Immutability
Refactoring to ImmutabilityRefactoring to Immutability
Refactoring to ImmutabilityKevlin Henney
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that LetterKevlin Henney
 
Educational slides by venay magen
Educational slides by venay magenEducational slides by venay magen
Educational slides by venay magenvenaymagen19
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsJohn De Goes
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In JavaAndrei Solntsev
 
Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1José Paumard
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Philip Schwarz
 
Porque aprender haskell me fez um programador python melhor?
Porque aprender haskell me fez um programador python melhor?Porque aprender haskell me fez um programador python melhor?
Porque aprender haskell me fez um programador python melhor?UFPA
 

Mais procurados (20)

Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Refactoring to Immutability
Refactoring to ImmutabilityRefactoring to Immutability
Refactoring to Immutability
 
Java and j2ee_lab-manual
Java and j2ee_lab-manualJava and j2ee_lab-manual
Java and j2ee_lab-manual
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
 
Haskell
HaskellHaskell
Haskell
 
Educational slides by venay magen
Educational slides by venay magenEducational slides by venay magen
Educational slides by venay magen
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In Java
 
Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
 
Stacks
StacksStacks
Stacks
 
Functional programming in java
Functional programming in javaFunctional programming in java
Functional programming in java
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
 
ROP
ROPROP
ROP
 
Stack, queue and hashing
Stack, queue and hashingStack, queue and hashing
Stack, queue and hashing
 
Porque aprender haskell me fez um programador python melhor?
Porque aprender haskell me fez um programador python melhor?Porque aprender haskell me fez um programador python melhor?
Porque aprender haskell me fez um programador python melhor?
 
ALF 5 - Parser Top-Down
ALF 5 - Parser Top-DownALF 5 - Parser Top-Down
ALF 5 - Parser Top-Down
 

Destaque

RESTful services with JAXB and JPA
RESTful services with JAXB and JPARESTful services with JAXB and JPA
RESTful services with JAXB and JPAShaun Smith
 
JPA 2.1 performance tuning tips
JPA 2.1 performance tuning tipsJPA 2.1 performance tuning tips
JPA 2.1 performance tuning tipsosa_ora
 
Nuts and Bolts of WebSocket Devoxx 2014
Nuts and Bolts of WebSocket Devoxx 2014Nuts and Bolts of WebSocket Devoxx 2014
Nuts and Bolts of WebSocket Devoxx 2014Arun Gupta
 
Java Tools and Technologies Landscape for 2014 (image gallery)
Java Tools and Technologies Landscape for 2014 (image gallery)Java Tools and Technologies Landscape for 2014 (image gallery)
Java Tools and Technologies Landscape for 2014 (image gallery)ZeroTurnaround
 
Lightning Components Workshop
Lightning Components WorkshopLightning Components Workshop
Lightning Components WorkshopGordon Bockus
 
Customer experience transformation utilities june 25th 2014 copy
Customer experience transformation  utilities june 25th 2014  copyCustomer experience transformation  utilities june 25th 2014  copy
Customer experience transformation utilities june 25th 2014 copyphilippklaus
 
Guidebook to Video Intros
Guidebook to Video IntrosGuidebook to Video Intros
Guidebook to Video IntrosFiverr
 
Punjabi Suits Online Shopping at Craft Shops India
Punjabi Suits Online Shopping at Craft Shops IndiaPunjabi Suits Online Shopping at Craft Shops India
Punjabi Suits Online Shopping at Craft Shops IndiaCraft Shops India
 
Presentacion maria power point
Presentacion maria power pointPresentacion maria power point
Presentacion maria power pointEsmeralda Martinez
 
Tracey Rancifer: 12 Tips on Staying Inspired
Tracey Rancifer: 12 Tips on Staying InspiredTracey Rancifer: 12 Tips on Staying Inspired
Tracey Rancifer: 12 Tips on Staying InspiredTracey Rancifer
 
The Numinous Place at Off The Page
The Numinous Place at Off The PageThe Numinous Place at Off The Page
The Numinous Place at Off The PageDean Johnson
 
TAFE 2017 - Sponsors & Social: The Art of Partnership Promotion
TAFE 2017 - Sponsors & Social: The Art of Partnership PromotionTAFE 2017 - Sponsors & Social: The Art of Partnership Promotion
TAFE 2017 - Sponsors & Social: The Art of Partnership PromotionSaffire
 
Anonymity & Privacy in the digital, public sphere.
Anonymity & Privacy in the digital, public sphere.Anonymity & Privacy in the digital, public sphere.
Anonymity & Privacy in the digital, public sphere.Christopher Grayson
 

Destaque (18)

RESTful services with JAXB and JPA
RESTful services with JAXB and JPARESTful services with JAXB and JPA
RESTful services with JAXB and JPA
 
Rest
RestRest
Rest
 
JPA 2.1 performance tuning tips
JPA 2.1 performance tuning tipsJPA 2.1 performance tuning tips
JPA 2.1 performance tuning tips
 
Nuts and Bolts of WebSocket Devoxx 2014
Nuts and Bolts of WebSocket Devoxx 2014Nuts and Bolts of WebSocket Devoxx 2014
Nuts and Bolts of WebSocket Devoxx 2014
 
Java Tools and Technologies Landscape for 2014 (image gallery)
Java Tools and Technologies Landscape for 2014 (image gallery)Java Tools and Technologies Landscape for 2014 (image gallery)
Java Tools and Technologies Landscape for 2014 (image gallery)
 
Lightning Components Workshop
Lightning Components WorkshopLightning Components Workshop
Lightning Components Workshop
 
Impacto De Las Ti Cs
Impacto De Las Ti CsImpacto De Las Ti Cs
Impacto De Las Ti Cs
 
Customer experience transformation utilities june 25th 2014 copy
Customer experience transformation  utilities june 25th 2014  copyCustomer experience transformation  utilities june 25th 2014  copy
Customer experience transformation utilities june 25th 2014 copy
 
Guidebook to Video Intros
Guidebook to Video IntrosGuidebook to Video Intros
Guidebook to Video Intros
 
Punjabi Suits Online Shopping at Craft Shops India
Punjabi Suits Online Shopping at Craft Shops IndiaPunjabi Suits Online Shopping at Craft Shops India
Punjabi Suits Online Shopping at Craft Shops India
 
Presentacion maria power point
Presentacion maria power pointPresentacion maria power point
Presentacion maria power point
 
Lean at Redbubble
Lean at RedbubbleLean at Redbubble
Lean at Redbubble
 
Tracey Rancifer: 12 Tips on Staying Inspired
Tracey Rancifer: 12 Tips on Staying InspiredTracey Rancifer: 12 Tips on Staying Inspired
Tracey Rancifer: 12 Tips on Staying Inspired
 
Meeting seminar 2 copy
Meeting seminar 2 copyMeeting seminar 2 copy
Meeting seminar 2 copy
 
The Numinous Place at Off The Page
The Numinous Place at Off The PageThe Numinous Place at Off The Page
The Numinous Place at Off The Page
 
TAFE 2017 - Sponsors & Social: The Art of Partnership Promotion
TAFE 2017 - Sponsors & Social: The Art of Partnership PromotionTAFE 2017 - Sponsors & Social: The Art of Partnership Promotion
TAFE 2017 - Sponsors & Social: The Art of Partnership Promotion
 
Opinen pitch deck_v1.2
Opinen pitch deck_v1.2Opinen pitch deck_v1.2
Opinen pitch deck_v1.2
 
Anonymity & Privacy in the digital, public sphere.
Anonymity & Privacy in the digital, public sphere.Anonymity & Privacy in the digital, public sphere.
Anonymity & Privacy in the digital, public sphere.
 

Semelhante a Java 8, lambdas, generics: How to survive? - NYC Java Meetup Group

computer notes - Data Structures - 35
computer notes - Data Structures - 35computer notes - Data Structures - 35
computer notes - Data Structures - 35ecomputernotes
 
Computer notes - Hashing
Computer notes - HashingComputer notes - Hashing
Computer notes - Hashingecomputernotes
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdffreddysarabia1
 
Legacy lambda code
Legacy lambda codeLegacy lambda code
Legacy lambda codePeter Lawrey
 
Applying Generics
Applying GenericsApplying Generics
Applying GenericsBharat17485
 
Writing beautiful code with Java 8
Writing beautiful code with Java 8Writing beautiful code with Java 8
Writing beautiful code with Java 8Sergiu Mircea Indrie
 
Array assignment
Array assignmentArray assignment
Array assignmentAhmad Kamal
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Andrew Petryk
 
Xebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalXebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalUrs Peter
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8franciscoortin
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#Shahzad
 
CS253: Priority queues (2019)
CS253: Priority queues (2019)CS253: Priority queues (2019)
CS253: Priority queues (2019)Jinho Choi
 

Semelhante a Java 8, lambdas, generics: How to survive? - NYC Java Meetup Group (20)

Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
computer notes - Data Structures - 35
computer notes - Data Structures - 35computer notes - Data Structures - 35
computer notes - Data Structures - 35
 
Computer notes - Hashing
Computer notes - HashingComputer notes - Hashing
Computer notes - Hashing
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
 
Legacy lambda code
Legacy lambda codeLegacy lambda code
Legacy lambda code
 
Applying Generics
Applying GenericsApplying Generics
Applying Generics
 
Writing beautiful code with Java 8
Writing beautiful code with Java 8Writing beautiful code with Java 8
Writing beautiful code with Java 8
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Java generics
Java genericsJava generics
Java generics
 
Array assignment
Array assignmentArray assignment
Array assignment
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
 
Xebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalXebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_final
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
 
Mysql1
Mysql1Mysql1
Mysql1
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8
 
Lesson11
Lesson11Lesson11
Lesson11
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
 
CS253: Priority queues (2019)
CS253: Priority queues (2019)CS253: Priority queues (2019)
CS253: Priority queues (2019)
 

Mais de Henri Tremblay

DevNexus 2020: Discover Modern Java
DevNexus 2020: Discover Modern JavaDevNexus 2020: Discover Modern Java
DevNexus 2020: Discover Modern JavaHenri Tremblay
 
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?Henri Tremblay
 
Confoo 2018: Être pragmatique
Confoo 2018: Être pragmatiqueConfoo 2018: Être pragmatique
Confoo 2018: Être pragmatiqueHenri Tremblay
 
DevNexus 2018: Learn Java 8, lambdas and functional programming
DevNexus 2018: Learn Java 8, lambdas and functional programmingDevNexus 2018: Learn Java 8, lambdas and functional programming
DevNexus 2018: Learn Java 8, lambdas and functional programmingHenri Tremblay
 
Do you know your mock? - Madras JUG 20171028
Do you know your mock? - Madras JUG 20171028Do you know your mock? - Madras JUG 20171028
Do you know your mock? - Madras JUG 20171028Henri Tremblay
 
Be Pragmatic - JavaOne 2017
Be Pragmatic - JavaOne 2017Be Pragmatic - JavaOne 2017
Be Pragmatic - JavaOne 2017Henri Tremblay
 
Confoo 2016: Initiation aux tests de charge
Confoo 2016: Initiation aux tests de chargeConfoo 2016: Initiation aux tests de charge
Confoo 2016: Initiation aux tests de chargeHenri Tremblay
 
Réactif, parallèle, asynchrone. Pourquoi!
Réactif, parallèle, asynchrone. Pourquoi!Réactif, parallèle, asynchrone. Pourquoi!
Réactif, parallèle, asynchrone. Pourquoi!Henri Tremblay
 
Microbenchmarking with JMH
Microbenchmarking with JMHMicrobenchmarking with JMH
Microbenchmarking with JMHHenri Tremblay
 
Vivre en parallèle - Softshake 2013
Vivre en parallèle - Softshake 2013Vivre en parallèle - Softshake 2013
Vivre en parallèle - Softshake 2013Henri Tremblay
 
Performance perpétuelle (Devopsdays Paris 2013)
Performance perpétuelle (Devopsdays Paris 2013)Performance perpétuelle (Devopsdays Paris 2013)
Performance perpétuelle (Devopsdays Paris 2013)Henri Tremblay
 
DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the ...
DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the ...DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the ...
DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the ...Henri Tremblay
 

Mais de Henri Tremblay (13)

DevNexus 2020: Discover Modern Java
DevNexus 2020: Discover Modern JavaDevNexus 2020: Discover Modern Java
DevNexus 2020: Discover Modern Java
 
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
 
Confoo 2018: Être pragmatique
Confoo 2018: Être pragmatiqueConfoo 2018: Être pragmatique
Confoo 2018: Être pragmatique
 
DevNexus 2018: Learn Java 8, lambdas and functional programming
DevNexus 2018: Learn Java 8, lambdas and functional programmingDevNexus 2018: Learn Java 8, lambdas and functional programming
DevNexus 2018: Learn Java 8, lambdas and functional programming
 
Do you know your mock? - Madras JUG 20171028
Do you know your mock? - Madras JUG 20171028Do you know your mock? - Madras JUG 20171028
Do you know your mock? - Madras JUG 20171028
 
Be Pragmatic - JavaOne 2017
Be Pragmatic - JavaOne 2017Be Pragmatic - JavaOne 2017
Be Pragmatic - JavaOne 2017
 
Confoo 2016: Initiation aux tests de charge
Confoo 2016: Initiation aux tests de chargeConfoo 2016: Initiation aux tests de charge
Confoo 2016: Initiation aux tests de charge
 
Réactif, parallèle, asynchrone. Pourquoi!
Réactif, parallèle, asynchrone. Pourquoi!Réactif, parallèle, asynchrone. Pourquoi!
Réactif, parallèle, asynchrone. Pourquoi!
 
Perf university
Perf universityPerf university
Perf university
 
Microbenchmarking with JMH
Microbenchmarking with JMHMicrobenchmarking with JMH
Microbenchmarking with JMH
 
Vivre en parallèle - Softshake 2013
Vivre en parallèle - Softshake 2013Vivre en parallèle - Softshake 2013
Vivre en parallèle - Softshake 2013
 
Performance perpétuelle (Devopsdays Paris 2013)
Performance perpétuelle (Devopsdays Paris 2013)Performance perpétuelle (Devopsdays Paris 2013)
Performance perpétuelle (Devopsdays Paris 2013)
 
DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the ...
DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the ...DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the ...
DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the ...
 

Último

20240330_고급진 코드를 위한 exception 다루기
20240330_고급진 코드를 위한 exception 다루기20240330_고급진 코드를 위한 exception 다루기
20240330_고급진 코드를 위한 exception 다루기Chiwon Song
 
Kawika Technologies pvt ltd Software Development Company in Trivandrum
Kawika Technologies pvt ltd Software Development Company in TrivandrumKawika Technologies pvt ltd Software Development Company in Trivandrum
Kawika Technologies pvt ltd Software Development Company in TrivandrumKawika Technologies
 
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...OnePlan Solutions
 
Watermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesWatermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesShyamsundar Das
 
OpenChain Webinar: Universal CVSS Calculator
OpenChain Webinar: Universal CVSS CalculatorOpenChain Webinar: Universal CVSS Calculator
OpenChain Webinar: Universal CVSS CalculatorShane Coughlan
 
Kubernetes go-live checklist for your microservices.pptx
Kubernetes go-live checklist for your microservices.pptxKubernetes go-live checklist for your microservices.pptx
Kubernetes go-live checklist for your microservices.pptxPrakarsh -
 
About .NET 8 and a first glimpse into .NET9
About .NET 8 and a first glimpse into .NET9About .NET 8 and a first glimpse into .NET9
About .NET 8 and a first glimpse into .NET9Jürgen Gutsch
 
ERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxAutus Cyber Tech
 
Cybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadCybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadIvo Andreev
 
How Does the Epitome of Spyware Differ from Other Malicious Software?
How Does the Epitome of Spyware Differ from Other Malicious Software?How Does the Epitome of Spyware Differ from Other Malicious Software?
How Does the Epitome of Spyware Differ from Other Malicious Software?AmeliaSmith90
 
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Jaydeep Chhasatia
 
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/MLBig Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/MLAlluxio, Inc.
 
Introduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptxIntroduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptxIntelliSource Technologies
 
online pdf editor software solutions.pdf
online pdf editor software solutions.pdfonline pdf editor software solutions.pdf
online pdf editor software solutions.pdfMeon Technology
 
eAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspectionseAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspectionsNirav Modi
 
Webinar - IA generativa e grafi Neo4j: RAG time!
Webinar - IA generativa e grafi Neo4j: RAG time!Webinar - IA generativa e grafi Neo4j: RAG time!
Webinar - IA generativa e grafi Neo4j: RAG time!Neo4j
 
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdfARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdfTobias Schneck
 
Your Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software TeamsYour Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software TeamsJaydeep Chhasatia
 

Último (20)

Program with GUTs
Program with GUTsProgram with GUTs
Program with GUTs
 
20240330_고급진 코드를 위한 exception 다루기
20240330_고급진 코드를 위한 exception 다루기20240330_고급진 코드를 위한 exception 다루기
20240330_고급진 코드를 위한 exception 다루기
 
Kawika Technologies pvt ltd Software Development Company in Trivandrum
Kawika Technologies pvt ltd Software Development Company in TrivandrumKawika Technologies pvt ltd Software Development Company in Trivandrum
Kawika Technologies pvt ltd Software Development Company in Trivandrum
 
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
 
Watermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesWatermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security Challenges
 
OpenChain Webinar: Universal CVSS Calculator
OpenChain Webinar: Universal CVSS CalculatorOpenChain Webinar: Universal CVSS Calculator
OpenChain Webinar: Universal CVSS Calculator
 
Sustainable Web Design - Claire Thornewill
Sustainable Web Design - Claire ThornewillSustainable Web Design - Claire Thornewill
Sustainable Web Design - Claire Thornewill
 
Kubernetes go-live checklist for your microservices.pptx
Kubernetes go-live checklist for your microservices.pptxKubernetes go-live checklist for your microservices.pptx
Kubernetes go-live checklist for your microservices.pptx
 
About .NET 8 and a first glimpse into .NET9
About .NET 8 and a first glimpse into .NET9About .NET 8 and a first glimpse into .NET9
About .NET 8 and a first glimpse into .NET9
 
ERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptx
 
Cybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadCybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and Bad
 
How Does the Epitome of Spyware Differ from Other Malicious Software?
How Does the Epitome of Spyware Differ from Other Malicious Software?How Does the Epitome of Spyware Differ from Other Malicious Software?
How Does the Epitome of Spyware Differ from Other Malicious Software?
 
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
 
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/MLBig Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
 
Introduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptxIntroduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptx
 
online pdf editor software solutions.pdf
online pdf editor software solutions.pdfonline pdf editor software solutions.pdf
online pdf editor software solutions.pdf
 
eAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspectionseAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspections
 
Webinar - IA generativa e grafi Neo4j: RAG time!
Webinar - IA generativa e grafi Neo4j: RAG time!Webinar - IA generativa e grafi Neo4j: RAG time!
Webinar - IA generativa e grafi Neo4j: RAG time!
 
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdfARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
 
Your Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software TeamsYour Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
 

Java 8, lambdas, generics: How to survive? - NYC Java Meetup Group

  • 1. 27 au 29 mars 2013 Java 8, Lambdas, Generics: How to survive? Henri Tremblay Java Champion tremblay.pro inc. @henri_tremblay http://blog.tremblay.pro NYC Java Meetup Group
  • 2. Loves IT Strategy Performance Productivity Great food! Do Open Source Henri Tremblay Try to be useful
  • 5. Java 7 End of Life
  • 8. Lambda = Fun with generics Stream<Tweet> stream = Tweet.TWEETS.stream(); Predicate<Tweet> lambda = t -> t.containsHashTag("#lambda"); Collector<Tweet, ?, Map<Boolean, List<Tweet>>> collector = Collectors.partitioningBy(lambda); return stream.collect(collector);
  • 9. What do I need to know? 9© OCTO 2011 Why
  • 10. What do I need to know? 10© OCTO 2011 Why Covariance
  • 11. What do I need to know? 11© OCTO 2011 Why Covariance Capture
  • 12. What do I need to know? 12© OCTO 2011 Why Covariance Capture Inference
  • 13. What do I need to know? 13© OCTO 2011 Why Covariance Capture Inference Erasure
  • 14. What do I need to know? 14© OCTO 2011 Why Covariance Capture Inference Erasure Bridge
  • 16. Dreaded warnings 16 Type safety: The expression of type List needs unchecked conversion to conform to List<String> Type safety: Unchecked cast from List<capture#1-of ?> to List<String>
  • 18. 27 au 29 mars 2013 Why 18© OCTO 2011
  • 19. Rule #1 A code compiling without warning should never ever cause a ClassCastException 19
  • 20. 27 au 29 mars 2013 Covariance 20
  • 21. Arrays Arrays are covariant: Number n = Integer.MAX_VALUE; Number[] list = new Integer[0]; Generics are not: List<Number> l = new ArrayList<Integer>(); // Illegal 21
  • 22. Why not? List<Integer> li = new ArrayList<Integer>(); List<Number> ln = li; // illegal ln.add(new Float(3.1415)); int i = li.get(0); // ClassCastException 22 Would work if covariant And allow to break rule #1
  • 23. Why for array? Integer[] list = // ... foo(list); public void foo(Object[] o) { // ... }
  • 24. Arrays and generics don’t mix well Can’t have an array of generics List<String>[] lsa = new List<String>[10];// illegal 24
  • 25. Exception List<?>[] l = new ArrayList<?>[3]; 25
  • 26. Because If it was allowed List<String>[] lsa = new List<String>[10]; // illegal Object[] oa = lsa; // OK (covariant) oa[0] = new ArrayList<Integer>(); // OK oa[0].add(42); String s = lsa[0].get(0); // bad 26
  • 27. 27 au 29 mars 2013 Capture 27
  • 28. Capture usually is Type List<?> bar(); <T> IExpectationSetters<T> expect(T value); void andReturn(T value); // Method of IExpectationSetters expect(bar()).andReturn(new ArrayList<String>()); And you get The method andReturn(List<capture#6-of ?>) in the type IExpectationSetters<List<capture#6-of ?>> is not applicable for the arguments (ArrayList<String>) 28
  • 29. Detail List<?> bar(); <T> IExpectationSetters<T> expect(T value); void andReturn(T value); expect(bar()).andReturn(new ArrayList<String>()); List<Capture#6> bar = bar(); IExpectationSetters<List<Capture#6>> es = expect(bar()); es.andReturn(List<Capture#6> value); 29
  • 30. Only solution We need to cast expect((List<String>) bar()).andReturn(new ArrayList<String>()); But still a warning Type safety: Unchecked cast from List<capture#6-of ?> to List<String> Framework coder tip: Try to never return a wildcard unless necessary 30 Tell to expect we want a List<String>
  • 32. Diamonds are a programmer best friend List<String> l = new ArrayList<>();
  • 33. How the compiler tells the type <T> T anyObject(T clazz) 33 The parameterDetermine the return value type
  • 34. How the compiler tells the type MyType var = <T> T anyObject() 34 Determine the return type The assigned variable
  • 35. But watch out with overloading public void foo(String s) public void foo(Object o) foo(anyObject()); 35 Can’t guess the type
  • 36. Trick #1 <T> T anyObject(Class<T> clazz) 36 Artificially give the type with a dedicated parameter Determine the return value type
  • 37. But how to pass a generic? public void foo(String s) public void foo(Object o) foo(anyObject(List<String>.class)); 37 Illegal
  • 38. Some solutions foo((String) anyObject()); foo((List<String>) anyObject()); // Warning 38 This would work But still doesn’t work for generics
  • 39. Trick #2 So the only solution is foo(EasyMock.<List<String>> anyObject()); … which sadly doesn’t support static imports foo(.<List<String>> anyObject()); // Illegal 39
  • 40. Trick #2 applied to Lambda return Tweet.TWEETS.stream() .collect( Collectors.<Tweet, Boolean, List<Tweet>, Map<Boolean, List<Tweet>>> groupingBy(t->t.containsHashTag("#lambda"), HashMap::new, ArrayList::new)); Return type: Map<Boolean, List<Tweet>>
  • 41. Lambda = Inference return Tweet.TWEETS.stream() .collect(Collectors .partitioningBy( t->t.containsHashTag("#lambda"));
  • 42. How did it do it? Tweet.TWEETS.stream() List<Tweet> list = Tweet.TWEETS; Stream<Tweet> stream = list.stream();
  • 43. How did it do it? Stream<Tweet> stream = list.stream(); R result = stream.collect(Collector<? super T, ?, R> collector); R result = stream.collect(Collector<? super Tweet, ?, R> collector);
  • 44. How did it do it? stream.collect(Collector<? super Tweet, ?, R> collector); Collector<T, ?, Map<Boolean, List<T>>> collector = Collectors.partitioningBy(Predicate<? super T> predicate); Collector<Tweet, ?, Map<Boolean, List<Tweet>>> collector = Collectors.partitioningBy(Predicate<? super Tweet> predicate);
  • 45. How did it do it? Predicate<? super Tweet> lambda = t -> t.containsHashTag("#lambda"); We now know that So the best t can be is a Tweet Predicate<? super Tweet> lambda = (Tweet t) -> t.containsHashTag("#lambda");
  • 46. Trick #3: Lambda inference Object o = (Runnable) () -> { System.out.println("hi"); }; Collections.sort(strings, (String a, String b) -> a.compareTo(b));
  • 48. Erasure… public void foo() { List<String> l = new ArrayList<String>(); for (String s : l) { System.out.println(s); } } No type public void foo() { List l = new ArrayList(); for (String s : l) { System.out.println(s); } } Compilation
  • 49. … or not erasure public class A extends ArrayList<String> {} public static void main(final String[] args) { ParameterizedType type = (ParameterizedType) A.class.getGenericSuperclass(); System.out.println( type.getActualTypeArguments()[0]); }  prints class java.lang.String 49
  • 50. Type class java.lang.reflect.Type • GenericArrayType • ParameterizedType • TypeVariable • WildcardType • Implemented by Class java.lang.reflect.GenericDeclaration Implemented by Class, Method, Constructor 50 New powers unleashed!
  • 51. Useful! class A {} abstract class BaseDao<T> { public T load(final long id) { // … } } class ADao extends BaseDao<A> {} 51© OCTO 2011
  • 52. Useful! @SuppressWarnings("unchecked") public T load(final long id) { ParameterizedType type = (ParameterizedType) getClass() .getGenericSuperclass(); Type actualType = type.getActualTypeArguments()[0]; return em.find((Class<T>) actualType, (Long) id); } ADao A BaseDao<A> Unsafe cast
  • 54. Everything seems normal… class A<T> { abstract void set(T value); } class B extends A<String> { String value; @Override void set(final String value) { this.value = value; } }
  • 55. But is not class B extends A { void set(String value) { this.value = value; } volatile void set(Object o){ set((String)o); } }
  • 56. Example A a = new B(); a.set(new Object()); But at runtime: java.lang.ClassCastException Raw type warning Perfectly compiling
  • 57. The actual problem being B.class.getDeclaredMethods() volatile void set(java.lang.Object) void B.set(java.lang.String) This Returns that And gives you no way to find out which method is bridged
  • 58. What about lambdas? public class A { public static void main(String[] args) { Method[] methods = A.class.getDeclaredMethods(); Arrays.stream(methods).forEach(m -> System.out.println(m + " " + m.isBridge() + " " + m.isSynthetic())); } } Prints this public static void A.main(java.lang.String[]) false false private static void A.lambda$0(java.lang.reflect.Method) false true
  • 59. Conclusion Who has learned something today? 59© OCTO 2011
  • 60. Useful links Nice lambda tutorial (in French): http://lambda.ninjackaton.ninja-squad.com/ Description of inference types on lambda: http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-final.html Everything on generics: http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html Hopefully everything on lambdas http://www.lambdafaq.org/

Notas do Editor

  1. Hors le fait que ça nous donne des magnifiques oneliners, on y croise une quantité particulièrement épique de génériques
  2. Malheureusement, quand on le sépare en petits morceaux, nous voyons apparaître des tonnes de génériques. La bonne nouvelle, c’est que ça s’est amélioré. La dernière fois que j’ai donné cette conférence, ça ressemblait plutôt à ça
  3. Et vous terminez, pas trop fier de vous et pas trop sûr d’avoir compris le problème avec un aborable SuppressWarning. Cette session a pour but de vous faire comprendre 1- Pourquoi vous avez ces erreurs 2- Pourquoi c’est fait comme ça 3- Comment c’est implémenté
  4. Et vous terminez, pas trop fier de vous et pas trop sûr d’avoir compris le problème avec un aborable SuppressWarning. Cette session a pour but de vous faire comprendre 1- Pourquoi vous avez ces erreurs 2- Pourquoi c’est fait comme ça 3- Comment c’est implémenté
  5. Et vous terminez, pas trop fier de vous et pas trop sûr d’avoir compris le problème avec un aborable SuppressWarning. Cette session a pour but de vous faire comprendre 1- Pourquoi vous avez ces erreurs 2- Pourquoi c’est fait comme ça 3- Comment c’est implémenté
  6. Et vous terminez, pas trop fier de vous et pas trop sûr d’avoir compris le problème avec un aborable SuppressWarning. Cette session a pour but de vous faire comprendre 1- Pourquoi vous avez ces erreurs 2- Pourquoi c’est fait comme ça 3- Comment c’est implémenté
  7. Et vous terminez, pas trop fier de vous et pas trop sûr d’avoir compris le problème avec un aborable SuppressWarning. Cette session a pour but de vous faire comprendre 1- Pourquoi vous avez ces erreurs 2- Pourquoi c’est fait comme ça 3- Comment c’est implémenté
  8. Et vous terminez, pas trop fier de vous et pas trop sûr d’avoir compris le problème avec un aborable SuppressWarning. Cette session a pour but de vous faire comprendre 1- Pourquoi vous avez ces erreurs 2- Pourquoi c’est fait comme ça 3- Comment c’est implémenté
  9. Emplit de désespoir vous ne savez pas trop comment vous en débarasser parce que toutes vos tentatives ne compilent pas.
  10. Emplit de désespoir vous ne savez pas trop comment vous en débarasser parce que toutes vos tentatives ne compilent pas.
  11. Et vous terminez, pas trop fier de vous et pas trop sûr d’avoir compris le problème avec un aborable SuppressWarning. Cette session a pour but de vous faire comprendre 1- Pourquoi vous avez ces erreurs 2- Pourquoi c’est fait comme ça 3- Comment c’est implémenté
  12. Par exemple, les arrays
  13. C’est cette règle qui a forcé plusieurs décisions de design et qui a par conséquent rendu notre ami le @SuppressWarning si fréquent. On en vient à ce demander comment ils auraient fait si les annotations n’étaient pas apparu au même moment.
  14. Par exemple, les arrays
  15. Les arrays sont covariants. Si on peut assigner un object d’un type donné à un autre type, alors on peut assigner un array d’objet à un array de l’autre type Par contre pour les génériques on ne peut pas. Il est illégal de faire la ligne du bas. Car, un code qui compile sans warning ne doit jamais jamais causé un ClassCastException
  16. Un exemple que vous avez sûrement déjà vu pour expliquer pourquoi c’est interdit. Comme vous voyez, si la covariance était permisse nous briserions la règle #1 Et pour un array
  17. Parce que pour un tableau, on a envie que ça ça passe
  18. On ne peut pas faire de tableau de génériques et c’est bien dommage. Une seule exception, un tableau de wildcard. Le wildcard étant un type quelconque, nous n’avons pas de soucis. Dans tous les autres cas c’est interdit pour la raison suivante
  19. On ne peut pas faire de tableau de génériques et c’est bien dommage. Une seule exception, un tableau de wildcard. Le wildcard étant un type quelconque, nous n’avons pas de soucis. Dans tous les autres cas c’est interdit pour la raison suivante
  20. Nous avons le cas suivant. Grâce une asticieuse utilisation de la covariance des arrays, si les arrays génériques étaient permis, nous briserions la règle numéro 1. En résumé, si les designers des génériques avaient laissé tomber la règle pour ce cas et laisser le bénéfice du doute au développeur, nous aurions échappé à plusieurs complexité. Je vous laisse juge de leur décision.
  21. Par exemple, les arrays
  22. Une méthode retourne un type en wildcard Pour garder la cohérence, le compilateur va fixer le type et l’appeler capture#6 pour s’assurer de la cohérence du type donné à T Pour les développeurs de framework, ne jamais retourner de wildcard si possible
  23. Une méthode retourne un type en wildcard Pour garder la cohérence, le compilateur va fixer le type et l’appeler capture#6 pour s’assurer de la cohérence du type donné à T Pour les développeurs de framework, ne jamais retourner de wildcard si possible
  24. Warning mandatory pour ne pas enfreindre la règle #1
  25. Par exemple, les arrays
  26. Lorsqu’il y a un paramètre, le compilateur prend le type du paramètre pour déterminer le type de retour. Cette pour cette raison que le syntaxe que vous voyez est apparu en Java 5. Le paramètre ne sert à rien sauf à fixer le type. Mais ça vous les savez sûrement déjà.
  27. Ensuite s’il n’y a pas de paramètre, le compilateur déduit le type à partir de la variable à laquelle elle est assignée. Mais ça ne marche pas à tous les coups.
  28. Dans les cas d’overloading par exemple. Impossible de deviner quelle méthode doit être appelé
  29. Un truc classique est d’ajouter un paramètre juste pour la bonne cause. C’est un contournement classique.
  30. Dans les cas d’overloading par exemple. Impossible de deviner quelle méthode doit être appelé
  31. Pour les lambda, il est très fort probable d’en avoir besoin. Vous avez ici l’exemple du début où je l’utilisais. Fort heureusement, ce n’est pas nécessaire dans la nouvelle API. Par contre, j’ai un peu de difficulté à vous promettre que ce sera toujours le cas. On touche du bois
  32. Par exemple, les arrays
  33. Everybody knows what is erasure? List<String> and ArrayList<String> got erasure The variable in the loop kept is type Boring, nous on va parler des cas où il n’y a pas d’erasure.
  34. Oh dear, no erasure On récupère la classe parent qui s’avère être générique et implémente donc l’interface ParameterizedType.
  35. Il y a eu un ajout de plusieurs interfaces. Elles sont passées presque complètement inaperçu mais peuvent être utile. Par exemple, l’exemple précédent peut servir à faire ça
  36. Par polymorphisme, le getClass() retourne ADao. Donc la superclass est BaseDao, et le type du paramètre générique est A. And yes, the dumb part if the SuppressWarnings. It comes come the (Class<T>) cast. Since the compiler can’t be sure that actualType is a Class, we get the warning. On ne peut pas s’en débarasser.
  37. Par exemple, les arrays
  38. Vous avez une classe générique étendue par un autre qui fixe le type à String. Rien de plus classique.
  39. Magie, à la décompilation, une nouvelle méthode est apparue. C’est le bridge. Elle ne sert à rien sauf à l’assurer c’est bien une String qui est passé en paramètre. Le volatile c’est parce que la modificateur de champs et de méthodes ont des codes communs. Donc en fait, le décompilateur (jad) a un petit bogue. Attention, Java Decompiler ne vous montrera pas le bridge, il le fait disparaitre. On ne le voit qu’avec Jad qui est moins futé.
  40. La règle #1 n’est pas enfreinte car nous avons un warning. Par contre, Java ajoute dans ce cas particulier une sur-protection. Impossible de s’en prémunir à la compilation. Tout est valide. Il fallait donc combler la faille pour empêcher un Object d’être assigné à une String et amener le chaos et l’anarchie dans la JVM. D’où, le bridge.
  41. Vous avez deux méthodes. L’une déléguant directement à l’autre. Si vous avez un framework faisant des proxies dynamiques ou de l’AOP, vous vous retrouvez avec deux méthodes instrumentées. Et c’est assez rare que c’est ce que vous aviez prévus. Résultat, plus rien ne marche. Par exemple, Spring qui utilise beaucoup de proxies, a dû implémenter une class nommée BridgeMethodResolver qui permet de trouver la méthode concrête appelée par le bridge. Et malheureusement, le JDK n’a pas prévu le coup donc il faut la déduire. C’est ce que j’avais de plus compliqué à vous montrer aujourd’hui. Passons donc à la conclusion.
  42. J’ai pas mal pataugé sur ces sujets car ils sont assez peu documentés. C’est pas simple mais on finit par s’y retrouver. La question qui me taraude maintenant c’est “Est-ce que vous connaissiez tout ça?” Pour m’assurez que je ne raconte pas que des banalités. Est-ce que chaque personne pourrait lever la main et me dire si vous avez appris au moins une chose aujourd’hui?
  43. Maurice Naftalin
  44. Oh dear, no erasure