SlideShare a Scribd company logo
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 131
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 132
Что нового в JDK 8
Александр Ильин
Архитектор тестирования JDK
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 133
The following is intended to outline our general product
direction. It is intended
for information purposes only, and may not be incorporated
into any contract.
It is not a commitment to deliver any material, code, or
functionality, and should not be relied upon in making
purchasing decisions. The development, release, and timing
of any features or functionality described for Oracle’s products
remains at the sole discretion of Oracle.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 134Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 16
Program
Agenda
 50+ изменений
 DateTime API
 Type annotations
 Profiles
 Lambda
http://openjdk.java.net/projects/jdk8/features
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 135
JDK 8
Java for Everyone
• Профайлы
• JSR 310 - Date & Time APIs
• Non-Gregorian calendars
• Unicode 6.1
• ResourceBundle
• BCP47 locale matching
●
Globalization & Accessibility
Innovation
• Lambda (замыкания)
• Language Interop
• Nashorn
Core Libraries
• “Параллельные” коллекции
Improvements in functionality
• Improved type inference
Security
• Ограничение doPrivilege
• NSA Suite B algorithm support
• Поддержка SNI Server Side
• DSA обновление FIPS186-3
• AEAD JSSE CipherSuites
Tools
• Управление компилятором
• JSR 308 – аннотации Java-
типов
• Нативные пакеты
• Инструменты для App Store
Client
●
Новые методы
развертывания
●
JavaFX 8
●
Public UI Control API
●
ПоддержкаEmbedded
●
Поддержка HTML5
●
3D формы и атрибуты
●
Система печати
General Goodness
• Улучшения в JVM
• No PermGen
• Производительность
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 136
Date & Time API: JSR 310
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 137
Instant start = Instant.ofEpochMilli(123450L);
Instant end = Instant.now();
Duration duration = Duration.ofSeconds(12);
Duration bigger = duration.multipliedBy(4);
Duration biggest = bigger.plus(duration);
Instant later = start.plus(duration);
Instant earlier = start.minus(duration);
Date & Time
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 138
LocalDate ld = LocalDate.of(2010, Month.DECEMBER, 3);
LocalDateTime ldt =
LocalDateTime.of(date, LocalTime.of(12, 33));
ZonedDateTime zdt = ZonedDateTime.of(dateTime, zoneId);
zdt = zdt.minus(12, HOURS);
long days = DAYS.between(date1, date2);
Period period = Period.between(date1, date2);
Date & Time
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 139
Type annotations: JSR 308
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1310
Аннотации в Java до Java 8
 @Target
– ANNOTATION_TYPE, CONSTRUCTOR, FIELD,
LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE
 @Retention
– SOURCE, CLASS, RUNTIME
 Поля, значения по умолчанию
– @Test(timeout=100)
– Primitive, String, Class, enum, array of the above
 Нет наследования
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1311
Аннотации в Java 8
 Могут быть использованы на любом использовании типа
– Информация на следующих слайдах ...
 @Target
– TYPE_PARAMETER, TYPE_USE
 Повторяющиеся аннотации
@
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1312
JSR 308: Annotations on Java Types (1)
 method receivers
public int size() @Readonly { ... }
 generic type arguments
Map<@NonNull String, @NonEmpty List<@Readonly Document>>
files;
 arrays
Document[][@Readonly] docs2 =
new Document[2] [@Readonly 12];
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1313
JSR 308: Annotations on Java Types (2)
 typecasts
myString = (@NonNull String)myObject;
 type tests
boolean isNonNull = myString instanceof @NonNull String;
 object creation
new @NonEmpty @Readonly List(myNonEmptyStringSet)
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1314
JSR 308: Annotations on Java Types (3)
 type parameter bounds
<T extends @A Object, U extends @C Cloneable>
 class inheritance
class UnmodifiableList implements @Readonly List<@Readonly T> { ... }
 throws clauses
void monitorTemperature() throws @Critical TemperatureException { ... }
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1315
Nullness checker
Если Nullness checker не рапортует ошибок для какой-либо
программы, тогда во время выполнения этой программы
никогда не будет брошено null pointer exception.
@Nullable Object obj; @NonNull Object nnobj;
...
nnobj.toString(); obj.toString();
nnobj = obj; obj = nnobj;
if (nnobj == null) ...
if (obj != null) {
nnobj = obj; //type refinement
}
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1316
Lock checker
Если Lock checker не рапортует ошибок для какой-либо
программы, тогда программа держит определенный монитор
каждый раз когда доступается до переменной.
 @GuardedBy – доступ разрешен только если держится
определенный монитор
 @Holding – вызов разрешен только если держится определенный
монитор
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1317
Lock checker
@GuardedBy("MyClass.myLock") Object myMethod() { ... }
@GuardedBy("MyClass.myLock") Object x = myMethod();
@GuardedBy("MyClass.myLock") Object y = x;
Object z = x;
x.toString();
synchronized(MyClass.myLock) {
y.toString();
}
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1318
Lock checker
void helper1(@GuardedBy("MyClass.myLock") Object a) {
a.toString();
synchronized(MyClass.myLock) {
a.toString();
}
}
@Holding("MyClass.myLock")
void helper2(@GuardedBy("MyClass.myLock") Object b) {
b.toString();
}
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1319
JDK profiles
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1320
base
tls logging
authjdbc
jtarmi
jaxp
naming
rowset
kerberos management
compiler
xmldsig
prefs
sctp
instrument
scripting
crypto
compat
management.iiop cosnaming
corba
desktop
tools.jre
jaxws
jx.annotations
httpserver
tools
tools.jaxws tools.base
devtools
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1321
base
tls logging
authjdbc
jtarmi
jaxp
naming
rowset
kerberos management
compiler
xmldsig
prefs
sctp
instrument
scripting
crypto
compat
management.iiop cosnaming
corba
desktop
tools.jre
jaxws
jx.annotations
httpserver
tools
tools.jaxws tools.base
devtools
52MB
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1322
base
tls logging
authjdbc
jtarmi
jaxp
naming
rowset
kerberos management
compiler
xmldsig
prefs
sctp
instrument
scripting
crypto
compat
management.iiop cosnaming
corba
desktop
tools.jre
jaxws
jx.annotations
httpserver
tools
tools.jaxws tools.base
devtools
52MB 24
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1323
base
tls logging
authjdbc
jtarmi
jaxp
naming
rowset
kerberos management
compiler
xmldsig
prefs
sctp
instrument
scripting
crypto
compat
management.iiop cosnaming
corba
desktop
tools.jre
jaxws
jx.annotations
httpserver
tools
tools.jaxws tools.base
devtools
52MB 1724
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1324
base
tls logging
authjdbc
jtarmi
jaxp
naming
rowset
kerberos management
compiler
xmldsig
prefs
sctp
instrument
scripting
crypto
compat
management.iiop cosnaming
corba
desktop
tools.jre
jaxws
jx.annotations
httpserver
tools
tools.jaxws tools.base
devtools
1052MB 1724
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1325
Lambda: JSR 335
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1326
Lambda
 Лямбда
(Object o) -> (o.toString());
 Ссылка на метод
Object::toString()
 Метод по умолчанию
Collection.forEach(java.util.function.Block)
 Collections
shapes.stream().filter(s s.getColor() == BLUE).
map(s s.getWeight()).sum();
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.27
Функциональные интерфейсы
Интерфейс с одним методом
●
Runnable, Comparator, ActionListener
●
Predicate<T>, Block<T>
Лямбда - экземпляр функционального интерфейса
Predicate<String> isEmpty = s s.isEmpty();
Predicate<String> isEmpty = String::isEmpty;
Runnable r = () {System.out.println(“Boo!”) };
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.28
Эволюция интерфейсов
 Палка о двух концах
– Гибкость
• Специфицирован только API
– Невозможно изменить
• Требуется менять все имплементации
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.29
Методы по умолчанию
interface Collection<E> {
default void forEach(Block<E> action) {
for (E e: this) action.apply(e);
}
default boolean removeIf(Predicate<? super E> filter) {
boolean removed = false; Iterator<E> each = iterator();
while ( each.hasNext() ) {
if ( filter.test( each.next() ) ) {
each.remove(); removed = true;
}
}
return removed;
}
}
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.30
Методы по умолчанию
Множественное наследование?
 Интерфейса
 Поведения
 Состояния
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.31
Методы по умолчанию
Множественное наследование?
 Интерфейса
 Поведения
 Состояния
было всегда
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.32
Методы по умолчанию
Множественное наследование?
 Интерфейса
 Поведения
 Состояния
было всегдабыло всегда
методы по умолчанию
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.33
Методы по умолчанию
Множественное наследование?
 Интерфейса
 Поведения
 Состояния
методы по умолчанию
было всегда
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.34
Методы по умолчанию
Множественное наследование?
1.Класс побеждает
2.Более специфичный интерфейс предпочтительней
3.Во всех остальных случаях пользователь должен предоставить
реализацию
 Интерфейса
 Поведения
 Состояния
было всегда
методы по умолчанию
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.35
Diamonds? Нет проблем!
interface A {
default void m() {…}
}
interface B extends A {…}
interface C extends A {…}
class D implements B, C {...}
A
B C
D
m
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.36
Diamonds? Нет проблем!
interface A {
default void m() {…}
}
interface B extends A {
default void m() {…}
}
interface C extends A {...}
сlass D implements B, C {...}
A
B C
D
m
m
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.37
Явное разрешение неоднозначности
interface A {
default void m() {…}
}
interface B {
default void m() {…}
}
class C implements A, B {
//Must implement/reabstract m()
void m() { A.super.m(); }
}
A B
D
m m
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.38
Cортировка
Collections.sort(people, new Comparator<Person>() {
public int compare(Person x, Person y) {
return x.getLastName().compareTo(y.getLastName());
}
});
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.39
Сортировка с лямбдой
Comparator<Person> byLastName
= comparing(p p.getLastName());
Collections.sort(people, byLastName);
Collections.sort(people, comparing(p
p.getLastName()));
people.sort(comparing(p p.getLastName()))
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.40
Сортировка с лямбдой
people.sort(comparing(Person::getLastName))
people.sort(comparing(Person::getLastName).reverse());
people.sort(comparing(Person::getLastName)
.compose(comparing(Person::getFirstName)));
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1341
Что нового в JDK 8
Александр Ильин
Архитектор тестирования JDK

More Related Content

PDF
Novidades do Java SE 8
PDF
Ascp
PPTX
Abaqus_hdf5_interOp
PPTX
PDF
JAX RS 2.0 - OTN Bangalore 2013
PDF
Cloud computing BI publication 1
PDF
spring-tutorial
Novidades do Java SE 8
Ascp
Abaqus_hdf5_interOp
JAX RS 2.0 - OTN Bangalore 2013
Cloud computing BI publication 1
spring-tutorial

Similar to Александр Ильин, Oracle (20)

PDF
As novidades do Java EE 7: do HTML5 ao JMS 2.0
PPTX
12_more_idea_things_about_oracle_12c.pptx
PDF
Introduction to JavaFX on Raspberry Pi
PPTX
JavaFX and JEE 7
PDF
Aplicações HTML5 com Java EE 7 e NetBeans
PPTX
Innovations in Oracle Database 12c - 2015
PPTX
A Importância do JavaFX no Mercado Embedded
PPTX
12 things about Oracle 12c
PPTX
whats-new-netbeans-ide-80.pptx
PDF
Java API for WebSocket 1.0: Java EE 7 and GlassFish
PDF
First Steps with Java Card
DOCX
Prisoner Management System
PDF
Coding for Desktop & Mobile with HTML5 & Java EE
PDF
Batch Applications for the Java Platform
PPTX
IOUG Collaborate 2014 ASH/AWR Deep Dive
PDF
JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)
PDF
B2 whats new with oracle exalogic worlds best foundation for applications
PDF
Java EE 7 - Novidades e Mudanças
PPTX
New PLSQL in Oracle Database 12c
PDF
Working with databases in Android
As novidades do Java EE 7: do HTML5 ao JMS 2.0
12_more_idea_things_about_oracle_12c.pptx
Introduction to JavaFX on Raspberry Pi
JavaFX and JEE 7
Aplicações HTML5 com Java EE 7 e NetBeans
Innovations in Oracle Database 12c - 2015
A Importância do JavaFX no Mercado Embedded
12 things about Oracle 12c
whats-new-netbeans-ide-80.pptx
Java API for WebSocket 1.0: Java EE 7 and GlassFish
First Steps with Java Card
Prisoner Management System
Coding for Desktop & Mobile with HTML5 & Java EE
Batch Applications for the Java Platform
IOUG Collaborate 2014 ASH/AWR Deep Dive
JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)
B2 whats new with oracle exalogic worlds best foundation for applications
Java EE 7 - Novidades e Mudanças
New PLSQL in Oracle Database 12c
Working with databases in Android
Ad

More from Nata_Churda (20)

PDF
Александра Алябьева "Поиск IT-специалистов. Шагнем за рамки привычного?"
PPT
Алексей Аболмасов "Критерии сильного HR-решения"
PPT
«Хайлоад в рассылке почты: как спать спокойно»
PDF
«Лучшие предложения aviasales.ru, или как не упустить важное среди 150 миллио...
PPT
«Механизмы обновления платформы и окружений пользователей в Jelastic»
PDF
«PRFLR - OpenSource инструмент для анализа производительности кода»
PPT
«Делимся опытом разработки высоконагруженных мобильных приложений на примере ...
PPT
«Как ради производительности высоконагруженного приложения мы разработали соб...
PDF
«Облачная платформа Windows Azure для высоконагруженных проектов»
PPT
Алена Новоселова, Яндекс.Деньги
PPTX
Артем Кумпель, ITmozg
PPTX
Белогрудов Владислав, EMC
PDF
Анатолий Кондратьев, Exigen Services
PDF
Алексей Николаенков, Devexperts
PDF
Анна Ященко, Google
PPTX
Акулов Егор, Mail.ru Group
PPTX
Елизавета Штофф, iChar
PPT
Шпунтенко Ольга, Mail.ru Group
PPT
Екатерина Евсеева, ITmozg
PDF
Александр Ильин, Oracle
Александра Алябьева "Поиск IT-специалистов. Шагнем за рамки привычного?"
Алексей Аболмасов "Критерии сильного HR-решения"
«Хайлоад в рассылке почты: как спать спокойно»
«Лучшие предложения aviasales.ru, или как не упустить важное среди 150 миллио...
«Механизмы обновления платформы и окружений пользователей в Jelastic»
«PRFLR - OpenSource инструмент для анализа производительности кода»
«Делимся опытом разработки высоконагруженных мобильных приложений на примере ...
«Как ради производительности высоконагруженного приложения мы разработали соб...
«Облачная платформа Windows Azure для высоконагруженных проектов»
Алена Новоселова, Яндекс.Деньги
Артем Кумпель, ITmozg
Белогрудов Владислав, EMC
Анатолий Кондратьев, Exigen Services
Алексей Николаенков, Devexperts
Анна Ященко, Google
Акулов Егор, Mail.ru Group
Елизавета Штофф, iChar
Шпунтенко Ольга, Mail.ru Group
Екатерина Евсеева, ITmozg
Александр Ильин, Oracle
Ad

Recently uploaded (20)

PDF
KodekX | Application Modernization Development
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Encapsulation theory and applications.pdf
PDF
Machine learning based COVID-19 study performance prediction
PDF
Electronic commerce courselecture one. Pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
Spectroscopy.pptx food analysis technology
PDF
Empathic Computing: Creating Shared Understanding
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
KodekX | Application Modernization Development
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
The AUB Centre for AI in Media Proposal.docx
NewMind AI Weekly Chronicles - August'25 Week I
Advanced methodologies resolving dimensionality complications for autism neur...
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Encapsulation theory and applications.pdf
Machine learning based COVID-19 study performance prediction
Electronic commerce courselecture one. Pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Network Security Unit 5.pdf for BCA BBA.
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Programs and apps: productivity, graphics, security and other tools
Spectroscopy.pptx food analysis technology
Empathic Computing: Creating Shared Understanding
Diabetes mellitus diagnosis method based random forest with bat algorithm

Александр Ильин, Oracle

  • 1. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 131
  • 2. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 132 Что нового в JDK 8 Александр Ильин Архитектор тестирования JDK
  • 3. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 133 The following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle.
  • 4. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 134Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 16 Program Agenda  50+ изменений  DateTime API  Type annotations  Profiles  Lambda http://openjdk.java.net/projects/jdk8/features
  • 5. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 135 JDK 8 Java for Everyone • Профайлы • JSR 310 - Date & Time APIs • Non-Gregorian calendars • Unicode 6.1 • ResourceBundle • BCP47 locale matching ● Globalization & Accessibility Innovation • Lambda (замыкания) • Language Interop • Nashorn Core Libraries • “Параллельные” коллекции Improvements in functionality • Improved type inference Security • Ограничение doPrivilege • NSA Suite B algorithm support • Поддержка SNI Server Side • DSA обновление FIPS186-3 • AEAD JSSE CipherSuites Tools • Управление компилятором • JSR 308 – аннотации Java- типов • Нативные пакеты • Инструменты для App Store Client ● Новые методы развертывания ● JavaFX 8 ● Public UI Control API ● ПоддержкаEmbedded ● Поддержка HTML5 ● 3D формы и атрибуты ● Система печати General Goodness • Улучшения в JVM • No PermGen • Производительность
  • 6. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 136 Date & Time API: JSR 310
  • 7. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 137 Instant start = Instant.ofEpochMilli(123450L); Instant end = Instant.now(); Duration duration = Duration.ofSeconds(12); Duration bigger = duration.multipliedBy(4); Duration biggest = bigger.plus(duration); Instant later = start.plus(duration); Instant earlier = start.minus(duration); Date & Time
  • 8. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 138 LocalDate ld = LocalDate.of(2010, Month.DECEMBER, 3); LocalDateTime ldt = LocalDateTime.of(date, LocalTime.of(12, 33)); ZonedDateTime zdt = ZonedDateTime.of(dateTime, zoneId); zdt = zdt.minus(12, HOURS); long days = DAYS.between(date1, date2); Period period = Period.between(date1, date2); Date & Time
  • 9. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 139 Type annotations: JSR 308
  • 10. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1310 Аннотации в Java до Java 8  @Target – ANNOTATION_TYPE, CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE  @Retention – SOURCE, CLASS, RUNTIME  Поля, значения по умолчанию – @Test(timeout=100) – Primitive, String, Class, enum, array of the above  Нет наследования
  • 11. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1311 Аннотации в Java 8  Могут быть использованы на любом использовании типа – Информация на следующих слайдах ...  @Target – TYPE_PARAMETER, TYPE_USE  Повторяющиеся аннотации @
  • 12. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1312 JSR 308: Annotations on Java Types (1)  method receivers public int size() @Readonly { ... }  generic type arguments Map<@NonNull String, @NonEmpty List<@Readonly Document>> files;  arrays Document[][@Readonly] docs2 = new Document[2] [@Readonly 12];
  • 13. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1313 JSR 308: Annotations on Java Types (2)  typecasts myString = (@NonNull String)myObject;  type tests boolean isNonNull = myString instanceof @NonNull String;  object creation new @NonEmpty @Readonly List(myNonEmptyStringSet)
  • 14. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1314 JSR 308: Annotations on Java Types (3)  type parameter bounds <T extends @A Object, U extends @C Cloneable>  class inheritance class UnmodifiableList implements @Readonly List<@Readonly T> { ... }  throws clauses void monitorTemperature() throws @Critical TemperatureException { ... }
  • 15. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1315 Nullness checker Если Nullness checker не рапортует ошибок для какой-либо программы, тогда во время выполнения этой программы никогда не будет брошено null pointer exception. @Nullable Object obj; @NonNull Object nnobj; ... nnobj.toString(); obj.toString(); nnobj = obj; obj = nnobj; if (nnobj == null) ... if (obj != null) { nnobj = obj; //type refinement }
  • 16. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1316 Lock checker Если Lock checker не рапортует ошибок для какой-либо программы, тогда программа держит определенный монитор каждый раз когда доступается до переменной.  @GuardedBy – доступ разрешен только если держится определенный монитор  @Holding – вызов разрешен только если держится определенный монитор
  • 17. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1317 Lock checker @GuardedBy("MyClass.myLock") Object myMethod() { ... } @GuardedBy("MyClass.myLock") Object x = myMethod(); @GuardedBy("MyClass.myLock") Object y = x; Object z = x; x.toString(); synchronized(MyClass.myLock) { y.toString(); }
  • 18. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1318 Lock checker void helper1(@GuardedBy("MyClass.myLock") Object a) { a.toString(); synchronized(MyClass.myLock) { a.toString(); } } @Holding("MyClass.myLock") void helper2(@GuardedBy("MyClass.myLock") Object b) { b.toString(); }
  • 19. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1319 JDK profiles
  • 20. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1320 base tls logging authjdbc jtarmi jaxp naming rowset kerberos management compiler xmldsig prefs sctp instrument scripting crypto compat management.iiop cosnaming corba desktop tools.jre jaxws jx.annotations httpserver tools tools.jaxws tools.base devtools
  • 21. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1321 base tls logging authjdbc jtarmi jaxp naming rowset kerberos management compiler xmldsig prefs sctp instrument scripting crypto compat management.iiop cosnaming corba desktop tools.jre jaxws jx.annotations httpserver tools tools.jaxws tools.base devtools 52MB
  • 22. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1322 base tls logging authjdbc jtarmi jaxp naming rowset kerberos management compiler xmldsig prefs sctp instrument scripting crypto compat management.iiop cosnaming corba desktop tools.jre jaxws jx.annotations httpserver tools tools.jaxws tools.base devtools 52MB 24
  • 23. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1323 base tls logging authjdbc jtarmi jaxp naming rowset kerberos management compiler xmldsig prefs sctp instrument scripting crypto compat management.iiop cosnaming corba desktop tools.jre jaxws jx.annotations httpserver tools tools.jaxws tools.base devtools 52MB 1724
  • 24. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1324 base tls logging authjdbc jtarmi jaxp naming rowset kerberos management compiler xmldsig prefs sctp instrument scripting crypto compat management.iiop cosnaming corba desktop tools.jre jaxws jx.annotations httpserver tools tools.jaxws tools.base devtools 1052MB 1724
  • 25. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1325 Lambda: JSR 335
  • 26. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1326 Lambda  Лямбда (Object o) -> (o.toString());  Ссылка на метод Object::toString()  Метод по умолчанию Collection.forEach(java.util.function.Block)  Collections shapes.stream().filter(s s.getColor() == BLUE). map(s s.getWeight()).sum();
  • 27. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.27 Функциональные интерфейсы Интерфейс с одним методом ● Runnable, Comparator, ActionListener ● Predicate<T>, Block<T> Лямбда - экземпляр функционального интерфейса Predicate<String> isEmpty = s s.isEmpty(); Predicate<String> isEmpty = String::isEmpty; Runnable r = () {System.out.println(“Boo!”) };
  • 28. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.28 Эволюция интерфейсов  Палка о двух концах – Гибкость • Специфицирован только API – Невозможно изменить • Требуется менять все имплементации
  • 29. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.29 Методы по умолчанию interface Collection<E> { default void forEach(Block<E> action) { for (E e: this) action.apply(e); } default boolean removeIf(Predicate<? super E> filter) { boolean removed = false; Iterator<E> each = iterator(); while ( each.hasNext() ) { if ( filter.test( each.next() ) ) { each.remove(); removed = true; } } return removed; } }
  • 30. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.30 Методы по умолчанию Множественное наследование?  Интерфейса  Поведения  Состояния
  • 31. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.31 Методы по умолчанию Множественное наследование?  Интерфейса  Поведения  Состояния было всегда
  • 32. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.32 Методы по умолчанию Множественное наследование?  Интерфейса  Поведения  Состояния было всегдабыло всегда методы по умолчанию
  • 33. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.33 Методы по умолчанию Множественное наследование?  Интерфейса  Поведения  Состояния методы по умолчанию было всегда
  • 34. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.34 Методы по умолчанию Множественное наследование? 1.Класс побеждает 2.Более специфичный интерфейс предпочтительней 3.Во всех остальных случаях пользователь должен предоставить реализацию  Интерфейса  Поведения  Состояния было всегда методы по умолчанию
  • 35. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.35 Diamonds? Нет проблем! interface A { default void m() {…} } interface B extends A {…} interface C extends A {…} class D implements B, C {...} A B C D m
  • 36. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.36 Diamonds? Нет проблем! interface A { default void m() {…} } interface B extends A { default void m() {…} } interface C extends A {...} сlass D implements B, C {...} A B C D m m
  • 37. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.37 Явное разрешение неоднозначности interface A { default void m() {…} } interface B { default void m() {…} } class C implements A, B { //Must implement/reabstract m() void m() { A.super.m(); } } A B D m m
  • 38. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.38 Cортировка Collections.sort(people, new Comparator<Person>() { public int compare(Person x, Person y) { return x.getLastName().compareTo(y.getLastName()); } });
  • 39. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.39 Сортировка с лямбдой Comparator<Person> byLastName = comparing(p p.getLastName()); Collections.sort(people, byLastName); Collections.sort(people, comparing(p p.getLastName())); people.sort(comparing(p p.getLastName()))
  • 40. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.40 Сортировка с лямбдой people.sort(comparing(Person::getLastName)) people.sort(comparing(Person::getLastName).reverse()); people.sort(comparing(Person::getLastName) .compose(comparing(Person::getFirstName)));
  • 41. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1341 Что нового в JDK 8 Александр Ильин Архитектор тестирования JDK