3. Bulgarian Java user group
• http://java-bg.org
• http://groups.google.com/group/bg-jug
4. Agenda
• Java 7 yes.. 7
• Java 8
– Static methods on interfaces
– Lamdas?
– Exact Numeric Operations
– Type Annotations
– Optional
– Date and Time
– Nashorn
5. Java 7
• We all know about diamond operator right?
– List<Integer> primes = new ArrayList<>();
• And Strings in switch
• And Fork Join Framework
• And Underscore in Numeric literals
– int billion = 1_000_000_000; // 10^9
• And maybe catching Multiple Exception Type in Single Catch
Block
– catch(ClassNotFoundException|SQLException ex)
• Binary Literals with prefix "0b“
– int binary = 0B0101_0000_1010_0010_1101_0000_1010_0010;
• G1 Garbage Collector
• And we all know about Automatic Resource Management
6. • But do we all know that we can use it with
multiple resources
try (PrintWriter catalogWriter = new PrintWriter(
new FileOutputStream(new File("d:/temp/catalog.csv")));
PrintWriter mediaWriter = new PrintWriter(
new FileOutputStream(new File("d:/temp/media.csv")))) {
…
}
7. And do you know about the “More
Precise Rethrowing of Exception”
• In Java version *.. yes we all know this is BAD
public void obscure() throws Exception {
try {
new FileInputStream("abc.txt").read();
new SimpleDateFormat("ddMMyyyy").parse("12-03-
2014");
} catch (Exception ex) {
System.out.println("Caught exception: " +
ex.getMessage());
throw ex;
}
}
10. The biggest two additions to Java 7
are.. ?
• 1) MethodHandle
Method handles gives us unrestricted
capabilities for calling non-public methods.
Compared to using the Reflection API, access
checking is performed when the method handle
is created as opposed to every time the method
is called.
13. And the second BIG addition to Java 7
is.. ?
• 2) invokedynamic
The culmination of invokedynamic is, of course,
the ability to make a dynamic call that the JVM
not only recognizes, but also optimizes in the
same way it optimizes plain old static-typed
calls.
14. What we all know? Before Java7 there
were 4 bytecodes for method
invocation
• invokevirtual - Invokes a method on a class.
• invokeinterface - Invokes a method on an
interface.
• invokestatic - Invokes a static method on a
class.
• invokespecial - Everything else called this way
can be constructors, superclass methods, or
private methods.
15. How invokedynamic look ?
invokevirtual #4 //Method
java/io/PrintStream.println:(Ljava/lang/St
ring;)V
invokedynamic #10
//NameAndTypelessThan:(Ljava/lang/Object;L
java/lang/Object;)
But wait. How does the JVM find the method if the
receiver type isn't supplied?
When the JVM sees an invokedynamic bytecode, it uses
the new linkage mechanism to get to the method it
needs.
16. How this works
Well … it uses a puzzle of 3 parts:
• AnonymousClassLoading provides a piece of that puzzle,
making it easy to generate lightweight bits of code suitable
for use as adapters and method handles.
• MethodHandle provides another piece of that puzzle,
serving as a direct method reference, allowing fast
invocation, argument list manipulation, and functional
composability.
• The last piece of the puzzle, and probably the coolest one
of all, is the bootstrapper.
(and we will speak about all that a bit later (~15 slides))
19. Yes.. but before the refresh on
lambdas: Static methods on interfaces
• You can declare static methods on interfaces:
public interface ContentFormatter {
public void format();
static String convertRegex(String
regex) {
...
}
}
20. Yes.. but before the refresh on
lambdas: Static methods on interfaces
• You can declare static methods on interfaces:
public interface ContentFormatter {
public void format();
static String convertRegex(String
regex) {
...
}
}
• None of the implementing classes will have this
method available to them
• The idea : less utility classes.. We all have
CollectionUtils right?
21. So..Lambdas… I see Lambdas
everywhere…
• Lambdas bring anonymous function types in Java
(JSR 335):
• Example:
(x,y) -> x + y
(parameters) -> {body}
22. Lambdas refresh
• Lambdas can be used in place of functional
interfaces (interfaces with just one method such
as Runnable)
• Example:
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("It runs!");
}
}
).start();
new Thread(() ->
System.out.println("It runs!")
).start();
24. This is NOT @FunctionalInterface
@FunctionalInterface
interface Test2 {
public default void doSomething() {}
}
25. This are valid @FunctionalInterface(s)
@FunctionalInterface
interface Test3 {
public void doSomething();
public default void doSomethingDefault() {}
}
@FunctionalInterface
interface Test4 {
public void doSomething();
public static void doSomethingDefault() {}
}
26. This look like a valid
@FunctionalInterface but is NOT and
can NOT be used as Lambda
@FunctionalInterface
interface Test5 {
public <T> T doSomething();
}
Lets suppose you have a method like this
public static void something(Test5 t){
System.out.println(t.doSomething());
}
27. This is Invalid :
something(() -> "cant do");
With Anonymous class.. (ugly one but is valid)… and with
unchecked cast warning (cuz of cast to Object WTF…)
something(new Test5() {
@Override
public <T> T doSomething() {
return (T) "hello";
}
});
28. So use generic classes..
@FunctionalInterface
@FunctionalInterface
interface Test6<T> {
public T doSomething();
}
29. And of course you can then consume
and use this like that
something(new Test6<Integer>() {
@Override
public Integer doSomething() {
return 5;
}
});
//or
something(() -> 5);
30. 2 notes about putting Lambdas on an
API
• Lets assume we had the following method pre
Java 8
public static void doIt(Integer a){}
• Let assume now.. That we want this integer to be
fetched lazy or via some method internally so we
may add another method like this:
public static void doIt(Callable<Integer> a){ }
So far so good.
31. However pre Java 8 we had a chance
to do this for the next API version:
public static void doIt(Integer a){
}
public static void doIt(String a){
}
But now .. we cant add this:
public static void doIt (Callable<Integer> a){
}
public static void doIt (Callable<String> a){
}
Because the generics are removed and this two methods
became the same so we got duplicated method. So this is
something we need to think about.
32. And also lets say we had only one
method with one generic type but we
want to use another interface
• So we had:
public static void doIt(Callable<Integer> a){
}
and we may add
public static void doIt(Supplier<Integer> a){
}
And that’s look fine… to us.
33. However when we want to call this
and type :
doIt(() -> 5);
Now we (in fact all clients that used our API) get
ambigous method.
And the only workaround for them is to change
their code to something like :
doIt((Callable<Integer>)() -> 5)
;
Which is… if first ugly and second it require manual
change(s) in the client code.
36. What, why … so not just syntax sugar ?
• Nope… if they were… we would have 1000
(one class per lambda) classes generated,
visible and loaded each time – no meter
invoked or not invoked in the current run.
• It creates complicated lookup and “type
profile pollution”
• The worst is that the first version Java
compiler emits will mean this will stay like that
FOREVER
37. How lambdas magic work in few
steps?
• Desugaring lambda to a method (static or instance)
• invokedynamic is used in the bytecode
• Bootstrap method is called which is simply a piece of
code that the JVM can call when it encounters a
dynamic invocation. It has all the information about
the call directly from the JVM itself.
• Bootstrap uses different translation strategies for
example MethodHandle to call right method, or code
generatation of an inner class . Currently it uses
“lambda metafactory” where it passes the
interface+the desugared method like lambda$1 which
returns an instance of the interface.
38. How this instance of an interface is
returned is up 2 the VM
implementation
• Metafactory can spin inner classes dynamically.
So generating the same class that the compiler
should but runtime
• Metafactory can create one wrapper class per
instance type ( So one for Predicate, one for
Runnable so on )- constructor takes method
handle, methods just invoke the method handle
• Dynamic proxies
• OR private VM APIs
39. Some performance tests pre-pre-pre
release (~2013)
Single threaded Saturated
Inner class 160 1407
Non capturing
lambdas
636 23201
Capturing lambdas 170 1400
Operations per microsecond
40. No more lambdas… today !
topic.next() -Exact Numeric Operations
• Java 8 has added several new “exact”
methods to the Math class(and not only)
protecting sensitive code from implicit
overflows
int safeC = Math.multiplyExact(bigA, bigB);
// will throw ArithmeticException if result exceeds +-2^31
41. BigInteger & BigDecimal
4 new methods added to BigInteger class (also to
BigDecimal)
longValueExact(),
intValueExact(),
shortValueExact(),
and byteValueExact().
and toBigIntegerExact() for BigDecimal
All of the newly introduced “xxxxxExact()” methods throw
an ArithmeticException if the number contained in
the BigInteger instance cannot be provided in the
specified form without loss of information
43. Annotations in Java 5/6/7
• Annotations on class declarations
@Stateless
public class Person
44. Annotations in Java 5/6/7
• Annotations on class declarations
@Stateless
public class Person
• Annotations on method declarations
@Override
public String toString() {
45. Annotations in Java 5/6/7
• Annotations on class declarations
@Stateless
public class Person
• Annotations on method declarations
@Override
public String toString() {
• Annotations on class fields
@PersistenceContext
private EntityManager em;
46. Annotations in Java 5/6/7
• Annotations on class declarations
@Stateless
public class Person
• Annotations on method declarations
@Override
public String toString() {
• Annotations on class fields
@PersistenceContext
private EntityManager em;
• Annotations on method parameters
public Person getPersonByName(@PathParam("name")
String name) {
47. New in Java 8
You can put annotations anywhere a type is
specified:
public void sayHello() {
@Encrypted String data;
List<@NonNull String> strings;
HashMap names = (@Immutable
HashMap) map;
}
49. Gotchas
• Nobody will stop you doing bad things:
public void passPassword(@Encrypted String pwd)
{}
public void hello() {
@PlainText String myPass = "foo";
passPassword(myPass);
}
• The code above will compile, run… and …crash
50. • You can’t override methods based on
annotations:
interface Test {
public void sayHello(@NotNull String notNull);
public void sayHelloNullable(String canNull);
}
class TestImpl implements Test {
@Override
public void sayHello(String notNull) {
// TODO Auto-generated method stub
}
@Override
public void sayHelloNullable(@NotNull String
notNull) {
// TODO Auto-generated method stub
}
}
52. How to access this annotation?
// get the email field
Field emailAddressField =
MyClass.class.getDeclaredField("emailAddresses");
// the field's type is both parameterized and annotated,
// cast it to the right type representation
AnnotatedParameterizedType annotatedParameterizedType =
(AnnotatedParameterizedType)
emailAddressField.getAnnotatedType();
// get all type parameters
AnnotatedType[] annotatedActualTypeArguments =
annotatedParameterizedType.getAnnotatedActualTypeArguments();
// the String parameter which contains the annotation
AnnotatedType stringParameterType =
annotatedActualTypeArguments[0];
// The actual annotation
Annotation emailAnnotation =
stringParameterType.getAnnotations()[0];
System.out.println(emailAnnotation); // @Email()
53. Method parameter names
• Before Java 8, only parameter positions and
types were preserved after compilation
• In Java 8 you can have those in the .class files
• They are not available by default
– Need to enable it with -parameters option to
javac
54. Getting parameter names
public static List<String> getParameterNames(Method
method) {
Parameter[] parameters = method.getParameters();
List<String> parameterNames = new ArrayList<>();
for (Parameter parameter : parameters) {
if(!parameter.isNamePresent()) {
throw new IllegalArgumentException("Parameter
names are not present!");
}
String parameterName = parameter.getName();
parameterNames.add(parameterName);
}
return parameterNames;
}
55. StringJoiner
• StringJoiner is used to construct a sequence of
characters separated by a delimiter and
optionally starting with a supplied prefix and
ending with a supplied suffix.
56. In Java 8 Example
The String "[George:Sally:Fred]" may be
constructed as follows:
StringJoiner sj =
new StringJoiner(":", "[", "]");
sj.add("George").add("Sally").add("Fred");
String desiredString = sj.toString();
57. Used internally in multiple places
List<String> cloudGroups = new
ArrayList<>();
cloudGroups.add("Cirrus");
cloudGroups.add("Alto");
cloudGroups.add("Stratus");
cloudGroups.add("Vertical Growth");
cloudGroups.add("Special Clouds"); String
cloudGroupsJoined = String.join(","
,cloudGroups);
59. Base64 encode/decode
// Encode
String asB64 =
Base64.getEncoder().encodeToString("some
string".getBytes("utf-8"));
System.out.println(asB64); // Output will be:
c29tZSBzdHJpbmc=
// Decode
byte[] asBytes =
Base64.getDecoder().decode("c29tZSBzdHJpbmc=");
System.out.println(new String(asBytes, "utf-
8")); // And the output is: some string
60. Optional
The main point behind Optional is to wrap
an Object and to provide convenience API to
handle nullability in a fluent manner.
Optional<String> stringOrNot =
Optional.of("123");
//This String reference will never be null
String alwaysAString =
stringOrNot.orElse("");
61. But lets first see a nice example by
Venkat Subramaniam
• Task is : Double the first even number greater
than 3
Having as example
List<Integer> values =
Arrays.asList(1,2,3,4,5,6,7,8,9,10);
62. Old way
int result = 0;
for(int e : values){
if(e > 3 && e% 2 == 0) {
result = e * 2;
break;
}
}
System.out.println(result);
Is it correct ? Is it ok ? .. Lets start eclipse
63. Ecilpse demo
So the new way :
System.out.println(
values.stream()
.filter(value -> value >3)
.filter(value -> value % 2 == 0)
.map(value -> value * 2)
.findFirst() );
Lets read it, cant be that hard? But lets start it in eclipse.
64. So in summary Optional is heavily used in
streaming API …! And you should think
how to use it ….TODAY!
// This Integer reference will be wrapped again
Optional<Integer> integerOrNot =
stringOrNot.map(Integer::parseInt);
// This int reference will never be null
int alwaysAnInt = stringOrNot
.map(s -> Integer.parseInt(s))
.orElse(0);
Arrays.asList(1, 2, 3)
.stream()
.findAny()
.ifPresent(System.out::println);
More at : http://java.dzone.com/articles/optional-will-remain-option
65.
66. Date and Time API
• The Date-Time API was developed using several
design principles.
– Clear: The methods in the API are well defined and
their behavior is clear and expected. For example,
invoking a method with a null parameter value
typically triggers a NullPointerException.
– Fluent. Because most methods do not allow
parameters with a null value and do not return
a null value, method calls can be chained together and
the resulting code can be quickly understood.
– Immutable
67. • The Date-Time API consists of the primary
package, java.time, and four subpackages:
• java.time
• java.time.chrono
• java.time.format
• java.time.temporal
• java.time.zone
68. Hint for the next slide
* Seconds are captured to nanosecond
precision.
**This class does not store this information, but
has methods to provide time in these units.
*** When a Period is added to a
ZonedDateTime, daylight saving time or other
local time differences are observed.
71. Method Naming Conventions in Date&Time API
Prefix Method Type Use
of static factory
Creates an instance where the factory is primarily validating
the input parameters, not converting them.
from static factory
Converts the input parameters to an instance of the target
class, which may involve losing information from the input.
parse static factory
Parses the input string to produce an instance of the target
class.
format instance
Uses the specified formatter to format the values in the
temporal object to produce a string.
get instance Returns a part of the state of the target object.
is instance Queries the state of the target object.
with instance
Returns a copy of the target object with one element
changed; this is the immutable equivalent to a set method
on a JavaBean.
plus instance
Returns a copy of the target object with an amount of time
added.
minus instance
Returns a copy of the target object with an amount of time
subtracted.
to instance Converts this object to another type.
at instance Combines this object with another.
73. LocalDate
LocalDate date = LocalDate.of(2000,
Month.NOVEMBER, 20);
DayOfWeek dotw = LocalDate.of(2012, Month.JULY,
9).getDayOfWeek();
LocalDate date = LocalDate.of(2000,
Month.NOVEMBER, 20);
TemporalAdjuster adj =
TemporalAdjusters.next(DayOfWeek.WEDNESDAY);
LocalDate nextWed = date.with(adj);
System.out.printf("For the date of %s, the next
Wednesday is %s.%n",date, nextWed);
//For the date of 2000-11-20, the next Wednesday
is 2000-11-22.
74. MonthDay & Year
MonthDay date = MonthDay.of(Month.FEBRUARY, 29);
boolean validLeapYear = date.isValidYear(2010);
boolean validLeapYear = Year.of(2012).isLeap();
77. Time Zone and Offset Classes
• ZoneId specifies a time zone identifier and
provides rules for converting between
an Instant and a LocalDateTime.
• ZoneOffset specifies a time zone offset from
Greenwich/UTC time.
78. Example
Set<String> allZones = new
TreeSet<String>(ZoneId.getAvailableZoneIds
());
LocalDateTime dt = LocalDateTime.now();
for (String s : allZones) {
ZoneId zone = ZoneId.of(s);
ZonedDateTime zdt = dt.atZone(zone);
ZoneOffset offset = zdt.getOffset();
System.out.printf(String.format("%35s
%10s%n", zone, offset));
…
Europe/Chisinau +03:00
Europe/Copenhagen +02:00
Europe/Dublin +01:00
Europe/Gibraltar +02:00
79. The Date-Time API provides three
temporal-based classes that work with
time zones:
• ZonedDateTime handles a date and time with a
corresponding time zone with a time zone offset
from Greenwich/UTC.
• OffsetDateTime handles a date and time with a
corresponding time zone offset from
Greenwich/UTC, without a time zone ID.
• OffsetTime handles time with a corresponding
time zone offset from Greenwich/UTC, without a
time zone ID.
80. ZonedDateTime
The ZonedDateTime class, in effect, combines
the LocalDateTime class with the ZoneId class. It
is used to represent a full date (year, month,
day) and time (hour, minute, second,
nanosecond) with a time zone (region/city, such
as Europe/Paris).
82. OffsiteDateTime
// Find the last Thursday in July 2013.
LocalDateTime date = LocalDateTime.of(2013, Month.JULY,
20, 19, 30);
ZoneOffset offset = ZoneOffset.of("-08:00");
OffsetDateTime date = OffsetDateTime.of(date, offset);
OffsetDateTime lastThursday =
date.with(TemporalAdjuster.lastInMonth(DayOfWeek.THURSD
AY));
System.out.printf("The last Thursday in July 2013 is
the %sth.%n",
lastThursday.getDayOfMonth());
//The last Thursday in July 2013 is the 25th.
.
83. Instant Class
• One of the core classes of the Date-Time API
import java.time.Instant;
Instant timestamp = Instant.now();
//2013-05-30T23:38:23.085Z
Instant oneHourLater =
Instant.now().plusHours(1);
84. Instant Class (2)
• There are methods for comparing instants,
such as isAfter and isBefore. The until method
returns how much time exists between
two Instant objects.
long secondsFromEpoch =
Instant.ofEpochSecond(0L).until(Instant.now(),
ChronoUnit.SECONDS);
85. Parsing
String in = ...;
LocalDate date = LocalDate.parse(in,
DateTimeFormatter.BASIC_ISO_DATE);
86. String input = ...;
try {
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("MMM d yyyy");
LocalDate date = LocalDate.parse(input,
formatter);
System.out.printf("%s%n", date);
}
catch (DateTimeParseException exc) {
System.out.printf("%s is not parsable!%n",
input);
throw exc; // Rethrow the exception.
}
// 'date' has been successfully parsed
88. Duration
Instant t1, t2;
...
long ns = Duration.between(t1, t2).toNanos();
Instant start;
...
Duration gap = Duration.ofSeconds(10);
Instant later = start.plus(gap);
A Duration is not connected to the timeline, in that it does not track time
zones or daylight saving time. Adding a Duration equivalent to 1 day to a
ZonedDateTime results in exactly 24 hours being added
90. Period
• To define an amount of time with date-based
values (years, months, days), use the Period class
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1);
Period p = Period.between(birthday, today);
long p2 = ChronoUnit.DAYS.between(birthday, today);
System.out.println("You are " + p.getYears() + " years, " +
p.getMonths() +
" months, and " + p.getDays() +
" days old. (" + p2 + " days total)");
//You are 53 years, 4 months, and 29 days old. (19508 days total)
91. calculate how long it is until your next
birthday
LocalDate birthday = LocalDate.of(1983, Month.OCTOBER, 28);
LocalDate nextBDay = birthday.withYear(today.getYear());
//If your birthday has occurred this year already, add 1 to the year.
if (nextBDay.isBefore(today) || nextBDay.isEqual(today)) {
nextBDay = nextBDay.plusYears(1);
}
Period p = Period.between(today, nextBDay);
long p2 = ChronoUnit.DAYS.between(today, nextBDay);
System.out.println("There are " + p.getMonths() + " months, and "
+ p.getDays() + " days until your next birthday. (" +
p2 + " total)");
92. Converting to/from a Non-ISO-Based
Date
LocalDateTime date = LocalDateTime.of(2013, Month.JULY,
20, 19, 30);
JapaneseDate jdate = JapaneseDate.from(date);
HijrahDate hdate = HijrahDate.from(date);
MinguoDate mdate = MinguoDate.from(date);
ThaiBuddhistDate tdate = ThaiBuddhistDate.from(date);
LocalDate date = LocalDate.from(JapaneseDate.now());
93. Legacy Date-Time Code
• Calendar.toInstant() converts the Calendar object to
an Instant.
• GregorianCalendar.toZonedDateTime() converts
a GregorianCalendar instance to a ZonedDateTime.
• GregorianCalendar.from(ZonedDateTime) creates
a GregorianCalendar object using the default locale from
a ZonedDateTime instance.
• Date.from(Instant) creates a Date object from an Instant.
• Date.toInstant() converts a Date object to an Instant.
• TimeZone.toZoneId() converts a TimeZone object to
a ZoneId
94. • The following example converts
a Calendar instance to
a ZonedDateTime instance. Note that a time
zone must be supplied to convert from
an Instant to a ZonedDateTime:
Calendar now = Calendar.getInstance();
ZonedDateTime zdt =
ZonedDateTime.ofInstant(now.toInstant(),
ZoneId.systemDefault()));
95. Instant inst = date.toInstant();
Date newDate = Date.from(inst);
Note : There is no one-to-one mapping
correspondence between the two APIs, but the
table on the next slide gives you a general idea
of which functionality in the java.util date and
time classes maps to the java.time APIs.
96. java.util Functionality java.time Functionality Comments
java.util.Date java.time.Instant
The Instant and Date classes are similar.
Each class:
- Represents an instantaneous point of time
on the timeline (UTC)
- Holds a time independent of a time zone
- Is represented as epoch-seconds (since
1970-01-01T00:00:00Z) plus nanoseconds
The Date.from(Instant) and Date.toInstant()
methods allow conversion between these
classes.
java.util.GregorianCale
ndar
java.time.ZonedDateTime
The ZonedDateTime class is the
replacement for GregorianCalendar. It
provides the following similar functionality.
Human time representation is as follows:
LocalDate: year, month, day
LocalTime: hours, minutes, seconds,
nanoseconds
ZoneId: time zone
ZoneOffset: current offset from GMT
The GregorianCalendar.from(ZonedDateTim
e) and GregorianCalendar.to(ZonedDateTim
e) methods faciliate conversions between
these classes.
97. java.util
Functionality
java.time
Functionality
Comments
java.util.TimeZone
java.time.ZoneId or
java.time.ZoneOffset
The ZoneId class specifies a time
zone identifier and has access to the
rules used each time zone.
The ZoneOffset class specifies only
an offset from Greenwich/UTC. For
more information, see Time Zone
and Offset Classes.
GregorianCalendar
with the date set
to 1970-01-01
java.time.LocalTime
Code that sets the date to 1970-01-
01 in a GregorianCalendar instance
in order to use the time
components can be replaced with
an instance of LocalTime.
99. Was ist das?
• Oracles runtime for ECMAScript 5.1
• GPL licensed
• Part of OpenJDK
• Released this march!
• Just type jjs in the shell… and you are in!
100. Why?
• Atwoods law: any application that can be written
in JavaScript, will eventually be written in
JavaScript
• Oracle proving ground for support of dynamic
languages
• Currently supports ECMAScript 5.1 (but 100%).
No backwards compatibility.
101. Why not Rhino
• All code compiled to bytecode. No
interpretation.
• JSR-223 javax.script.* is the only public API.
108. Simple
var timer = new java.util.Timer();
timer.schedule(
new java.util.TimerTask({
run: function(){
print("Tick")
}
})
,0,1000)
java.lang.Thread.sleep(5000)
timer.cancel();
109. Even more simple
var timer2= new java.util.Timer();
timer2.schedule(function(){print("Tack")},
0,1000)
java.lang.Thread.sleep(5000)
timer2.cancel();
110. Construct Java(Script) object
• var linkedList = new
java.util.LinkedList()
• var LinkedList = java.util.LinkedList
var list = new LinkedList()
• var LinkedList =
Java.type(“java.util.LinkedList”)
var list = new LinkedList()
111. Types
var ints = new (Java.type(“int[]”))(6)
ints[0]=1
ints[1]=1.6
ints[2]=null
ints[3]=“45”
ints[4]=“str”
Ints[5]=undefined
print(ints)
print(java.util.Arrays.toString(ints))
Output will be:
[I@43re2sd
[1, 1, 0, 45, 0, 0]
113. Type conversion
• Passing JavaScript values to Java methods will
use all allowed Java method invocation
conversions… + all allowed JavaScript
conversions
• All native JS objects implement java.util.Map
• And they do not implement java.util.List
115. Type conversion 2
MyJavaClass.about(123);
// class java.lang.Integer
MyJavaClass.about(49.99);
// class java.lang.Double
MyJavaClass.about(true);
// class java.lang.Boolean
MyJavaClass.about("hi there")
// class java.lang.String
MyJavaClass.about(new Number(23));
// class jdk.nashorn.internal.objects.NativeNumber
MyJavaClass.about(new Date());
// class jdk.nashorn.internal.objects.NativeDate
MyJavaClass.about(new RegExp());
// class jdk.nashorn.internal.objects.NativeRegExp
MyJavaClass.about({foo: 'bar'});
// class jdk.nashorn.internal.scripts.JO4
116. Arrays conversions
• Not converted automatically!
• Explicit APIs provided:
– var javaArray = Java.toJavaArray(jsArray,type)
– var jsArray = Java.toJavaScriptArray(javaArray)
117. Static accesses
Output:
:
/
var ps = java.io.File.pathSeparator
print(ps)
var File = Java.type("java.io.File")
var p = File.separator
print(p)
123. Scripting extensions
• Additional classpath elements can be specified
for the Java Virtual Machine (JVM).
• JavaScript strict mode can be activated.
• An intriguing scripting mode can be enabled.
127. What we(well… ok I) didn’t speak
about? …
• Streaming API (but I guess Nikolay Tomitov spoke
about this .. few )
• Stamped Locks
• Concurrent Adders
• Parallel Streams showing why the streaming API
is so f*cking awesome
• JavaFX
• Secure Random generation
• AND A LOT MORE
(check this out www.baeldung.com/java8 )
The invokevirtual part of the instruction is the one-byte operation code. The remainder of the instruction, #4, is the two-byte operand, which provides information about the method call in an abstract way. The operand refers to an entry in a pool of constants.
Type profile pollution in short – the VM says I don’t know what type I gonna see here.. I already saw 1001 of them … so I am gonna fallback full virtual dispatch instead of inline or caching and etc.
@Brian Goetz
All four of the newly introduced “xxxxxExact()” methods throw an ArithmeticException if the number contained in the BigInteger instance cannot be provided in the specified form without looss of information. BigInteger already had methods intValue() andlongValue() as well as inherited (from Number) methods shortValue() and byteValue()
Is it correct ? Is it ok ? .. Lets start eclipse. The idea here is that it makes you think.. But what about if no such number is found you got a bug since it prints 0 … as 0 is the first even number greater then 3 multiplied by 2…
You will notice it says Optional[8] so this is even a HINT hey.. this can be a null man…NOTE: you can extract the checks inside a methods that says isEven() and so on to be really easy to read and understand
Yes.. It has issues…you can read more here http://java.dzone.com/articles/optional-will-remain-option?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+javalobby%2Ffrontpage+%28Javalobby+%2F+Java+Zone%29
java.time
The core of the API for representing date and time. It includes classes for date, time, date and time combined, time zones, instants, duration, and clocks. These classes are based on the calendar system defined in ISO-8601, and are immutable and thread-safe.
java.time.chrono
The API for representing calendar systems other than the default ISO-8601. You can also define your own calendar system. This tutorial does not cover this package in any detail.
java.time.format
Classes for formatting and parsing dates and times.
java.time.temporal
Extended API, primarily for framework and library writers, allowing interoperations between the date and time classes, querying, and adjustment. Fields (TemporalField and ChronoField) and units (TemporalUnit and ChronoUnit) are defined in this package.
java.time.zone
Classes that support time zones, offsets from time zones, and time zone rules. If working with time zones, most developers will need to use only ZonedDateTime, and ZoneId or ZoneOffset.
* Seconds are captured to nanosecond precision.
** This class does not store this information, but has methods to provide time in these units.
*** When a Period is added to a ZonedDateTime, daylight saving time or other local time differences are observed.
* Seconds are captured to nanosecond precision.
** This class does not store this information, but has methods to provide time in these units.
*** When a Period is added to a ZonedDateTime, daylight saving time or other local time differences are observed.