Proposals for new function in Java SE 9 and beyond
-
Upload
barry-feigenbaum -
Category
Software
-
view
193 -
download
5
description
Transcript of Proposals for new function in Java SE 9 and beyond
![Page 1: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/1.jpg)
Potential Java JSR ItemsCommunity Input to Java SE 9+
Barry Feigenbaum, [email protected]
10/20/2014
Java SE only; no Java EE items
![Page 2: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/2.jpg)
Background
• Suggestions for inclusion into Java SE 9+– Intended to be the basis for multiple JSRs
• See http://futurejava.wordpress.com for discussion
![Page 3: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/3.jpg)
Now, What Shall We Talk About?
• Way to much to cover in one session– > 400 slides in this presentation alone– 100s of pages of backing details (as draft JSRs)
• Goal is to peek interest in pursuing next steps– Pruning/Defining/Authoring/Submitting JSRs– Guiding JSRs through JCP• JSR Committee• Reference Implementation • Technology Compatibility Kit
See https://www.jcp.org/en/jsr/proposal (may need to be JCP member to see this; free to sign up)
![Page 4: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/4.jpg)
Expectations of Ya’All
1. Provide feedback– On stated priorities– On stated definition of items (alternate approaches)– Potential implementation Gotchas/Flaws
2. Suggest items to add/remove from my catalog– Likely many not thought of– Items outside original scope (next slide)– Prune lower value items
3. Signup to help make progress
![Page 5: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/5.jpg)
Why these particular JSRs (in Brief)
1. ↓ Java Boilerplate/Learning Curve– Continue trend of recent Java/JRE editions– Automate several common idioms
2. ↓ JRE Inconsistencies– Ex. size() vs. length() vs. getLength()– Ex. differences between primitives and wrappers
3. ↑ Capability / Conciseness – More competitive with C#, Groovy, Scala, etc.
• Yet backward compatible; minimal JVM hit
![Page 6: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/6.jpg)
Presentation Content
• Three – Three – Three Presentations in One!1. Briefs (title + 1ish examples)
Tonight’s content2. Teasers (extended examples)
Better justification3. Details (implementation info)
Read this before submitting critiques / suggestions
![Page 7: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/7.jpg)
Individual Items List
• ~ 80 suggested items– Across multiple categories– Development cost varies radically (from trivial to
man months)• Item Catalog to follow…– Will skip lower priority items due to time limits– In no particular order– Some overlap between items– Some may have a history
BAF’s strawman prioritiesViolet – Very HighRed – HighYellow – MediumBlue - Low
![Page 8: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/8.jpg)
BRIEFS
![Page 9: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/9.jpg)
Major Item Category List
• Operator Overloading• Import Enhancements/Aliases• New Collection Types• New Numeric Types **• Parallel Processing Enhancements• Reduced Boilerplate in Source• Miscellaneous/Ease-of-Use Enhancements
Many items depend on each other for success
** make Java more viable for science/engineering (not just web apps)
![Page 10: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/10.jpg)
Enhanced Auto-boxing
• Auto–box primitive on method call– Significant move to equate primitives/wrappers• Primitives need to exist only as dense form for arrays
– Allows many new operations on “primitives”• Add methods to Boolean, Character, Number
subclasses
– Ex. int x = 1; x.toHexString() new Integer(x).toHexString()1.upto(10, x -> { System.out.println(x); })
![Page 11: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/11.jpg)
Operator “Overloading”
• Map operators to methods (compiler)– Operator methods are ordinary instance methods• Can call; can be overloaded; select visibility; etc.
– Ex. a + b a.$plus(b) or b.$iplus(a) **– Ex. a += 3 a.$aplus(3)
• Implement in many JRE classes– Operator and conversion methods– Collections, streams, numeric classes for sure– Static Object.sameAs(Object x, Object y) vs. ==
** Operator method name syntax TBD. $xxx, _xxx_, etc.
![Page 12: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/12.jpg)
Operator “Overloading”
• Overload-able Operators– + - * / \ % ** ++ -- & | ^ ~ < <= > >= == != ?= >> >>> << <<< [] []= (…) (type) :: ==> <== ... >.. ..<
– :x x: (where “x” is + - * / \ % & | ~ ^ < >)
• Ex. Using example type Foobar– Foobar r, g, b, x = r + 2 * g + ++b; – Foobar x = r.$plus(g.$imult(2)).$plus(b.$pinc());
implies new operator; italics implies new capability; :: may need to be :::
![Page 13: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/13.jpg)
Example Implementation
• In BigInteger– public BigInteger $plus(BigInteger other) =
this.add(other);– public BigInteger $plus(String other) =
this + new BigInteger(other);– public BigInteger $iplus(Integral other) =
new BigInteger(other.toString()) + this;– public <T> T $cast(Class<T> type) =
(T)this.doubleValue();
Only a partial set, many more for full implementation
![Page 14: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/14.jpg)
Code Safety Operators
• Safe Dereference (.?)– Ex. anAddress.?city
anAddress != null ? anAddress.city **: null;– Annotation/switch to make all “.” act like “.?”
• Safe Defaulted (?:) (AKA Elvis)– Ex. int x = anInt ?: -1
int x = new Integer(anInt).ifTrue() ? anInt : -1;– On any type implementing Truthful (ex. Number)– Left == null is always false so right returned
**: must be reference type
![Page 15: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/15.jpg)
Enhanced Concurrency
• Parallel For Loop – Ex. parallelfor(var x: <iterable> {, Map}) { … }– Exception/break ends all; continue ends current– Need to synchronized/use atomic values
• Message Passing Actor Model– Ex. {subject: “init”, data:”default”} ==> anActor;– Loosely-coupled Actor-based message processing– Hides most threading issues from users
![Page 16: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/16.jpg)
Dynamic Extensions
• var/VAR declaration with static type inference– Ex. var map = new HashMap<String, Integer>()
• Left-side generic type inference– Ex. Map<> map = new HashMap<String, Integer>()
• @dynamic Object/Object[] (duck typing)– Ex. @dynamic Object duck = new …
duck.quack(10); duck.die();– Semantics based on use of reflection
![Page 17: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/17.jpg)
Dynamic Extensions
• Method Literals– Ex. var m = String.substring(int, int);
• Method Bindings (sync & async)– var x = String.substring(int,it)::”Hello World!”;– var hello = x(0,6); or x…0; var hello = x(6);
• Static Object.as (vs. instanceof) Type Testing– Ex. Object o = ...; var p = as(Person.class, o)
Ex. var z = as(Integer.class, x, x -> { return x * 2; })
![Page 18: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/18.jpg)
Dynamic Extensions
• SupportsPseudoMethods ** interface– Allows receiver to support “virtual” methods– Often implemented via switch on method name– See teasers for an example
• Pseudo-implementation of interface– “implements” clause not required– Ex. void xxx(@conforms AnInterface x) {
x.aMethodInAnInterface(); }
– Parameter x can have any type with method aMethodInAnInterface()
** suggest better name
![Page 19: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/19.jpg)
New Collection Support
• Immutable (indexed) Tuple– Ex. var t = (1, “Hello”, 4.1, new Date(), (1, ’a’));– Ex. (var x, var y, var z) = (10, “hello!”, (-1, ‘c’));
• Immutable (Nil or head::tail) List– Ex. var t = (1::(“Hello”::(4.1::(new Date()::Nil)))) ;– Ex. var t = 1::“Hello”::4.1::new Date()::Nil
if “::” is right-associative operator
Use of “::” may be problematic so some other operator may be used.
![Page 20: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/20.jpg)
New Collection Support
• Immutable (persistent) Map– Ex. var t = (immutable) {“a”: 1, “c” 2};
t = (t[“b”] = 3);– Smart copy on write
• Immutable (sequential/wrapper) Range– Ex. var t = 0...99, u = 0..<100…2, v = start>..end– Ex: var s1 = “123456”[1…5] “2345”– Ex: var s2 = “123456”[-1…-5] “3456”– Ex. var rx = (1,2,3, …, 100).asRange() == 1…100
![Page 21: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/21.jpg)
New Collection Support
• Literals for List-like & Map types– Ex. [1, 2, 3] ** ArrayList by default– Ex. {a:1, b:2, c:3 } ** LinkedHashMap by default– Nested list/map allowed
• Initializers for all List-like & Map types– Ex. new Xlist() [1,2,3]; or new Xlist([1,2,3])
• New Collection Cast– mutable immutable
** May need to use #[…] and #{…} syntax
![Page 22: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/22.jpg)
New Numeric Support
• Immutable numeric Rational, Complex, UnitValue (and Unit)– Ex. var r = 5:/(long)7e12, c1 = 1e6 + 1.2e-3j,
c2 = 0.5 :< Pi / 2, kg = 1000 * gram; • Mutable Dense N-Dimensional Matrix– Ex. var t = Matrix.make(Integer.TYPE, 10, 10, 10)– Bit, numbers, Boolean,
char, reference
![Page 23: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/23.jpg)
New Numeric Support
• @checked (detect under/overflow) methods – Ex. @check int shift(int x, int y) { return x << y; }– Consider annotation/switch to disable shift size
restrictions• Power (xy via **) operator– Ex. var z = 2 ** 15; var sqrt = 101 ** 0.5;
• Literals for all (single part) numeric types– Ex. BigInteger: 0x123456789abcdef00000000X – Ex. BigDecimal: -123456789.987654321e400B
![Page 24: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/24.jpg)
String Extensions
• Multi-line - ″ ″ ″ text that can span lines ″ ″ ″• Raw - ″\n not an escape″R (R|r)• Specialized toString (debug & human forms)– Can implements in parts
• Brief - `thisIsaString• Interpolated - ~″${name} is ${age} old.″• Executed – var outs = ~`ls *.out`
![Page 25: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/25.jpg)
Aliases
• Create type aliases– Ex. typealias List<String> as SList– Ex. typealias String as string
• Create method aliases– Ex. methodalias String.length(void) as size
• @alias methods– Ex. @alias(“newName”) void oldName() { .. }
• @alias fields– Ex. @alias(“x, y, z”) int _x;
![Page 26: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/26.jpg)
Import Extensions
• Alias during import– Ex. import java.util.StringBuffer as|add SB
• Terse Imports– Ex. import java.swing.J* as *– Ex. import java.swing.JFrame as f:JPanel as p
• Method/Block Nested Imports– Ex. for(…) { import java.swing.*; … }– Ex. import java.swing.* { … }
• Package imports– Ex. import java.swing as s; s.JFrame f = new …
![Page 27: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/27.jpg)
Method Parameter Extensions• Defaulted Positional Parameters
– Ex. void xxx(int a, int b = 2, var c = 3L)• Floating Named Parameters
– Ex. invoke(-1, -2, {“a”:1, ”b”:2, “c”;3})– Ex. invoke(-1, -2, a:1, b:2, c:3)– Ex. invoke(c:3, b:2, -1, a:1, -2)– All named passed to last arg Map<String, Object>
• Reference (in+out) Parameters– Ex: @ref int x = 1, y = 2; (may promote to Integer)
public void swap(@ref int a, @ref int b) { int t = a; a = b; b = t;}
– swap(x, y); x == 2, y == 1
![Page 28: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/28.jpg)
Method Extensions
• Pseudo Instance Methods from Static– Ex. “%s is %s!”.format(“John”, “bad”)
String.format(“%s is %s!”, “John”, “bad”)• Full-Capture Values (AKA full Closures)– Ex. @ref int x; … (a) -> { return a + ++x; }– Value lives in heap (wrapped if needed)
• Terse (non-void) Methods– Ex. int x; int getX() = x; int getX() = { result = x; }
![Page 29: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/29.jpg)
Switch Extensions
• Use any type in Switch – Ex. Class x = …; switch(x) { case String.class: … }
• Add “select” statement (switch w/auto break)– Ex: select (x) { case 1: …; case 2: …; default: …; }
• Add multi-match: case x, y, x:– Ex. select(x) { case 1, 2: …; case 3: …; }
• Add goto <case> (vs. break)– Ex. case 1: …; break; case 2: … ; goto 1;
![Page 30: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/30.jpg)
Text Enhancements
• Add basic XML support on Map<String, String> contains List<XmlElement>– Ex. var xml= XmlElement.parse(“””<data>
<v id=“x” value=“1” />… </data>”””);• Add basic JSON support on Map<String, ?>– Ex. var json = JsonObject.parse(“{ x: 1, y: 2, z: 3}”);
• Extend Appendable method set – Ex. Appendable a = …;
a.appendln(“a”); a.appendf(“%d”, 10 * 20)
![Page 31: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/31.jpg)
Enhanced Structure
• Services Model - Find/Manage/Update/ Dependency Injection– Ex. See teasers for example– Dynamic (in process) Service Location & Binding
• Duplicate Interface Method Implementation– Ex. interface A { x(); } interface B { x(); }
class AB implements A, B { x() { A.x(); } A.x() { … } B.x() { … } }
![Page 32: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/32.jpg)
Enhanced Structure
• @const References– Ex. @const Person p = new Person();
p.name =“x”; compiler error– Applies to use of p; not to Person
• @immutable Types– Ex. @immutable class Xxx { public int x; }
Xxx i = ...; i.x = 1; compiler error• @pure (cacheable) Methods – Ex. @pure Object x() { … }
Object p = x(), q = x(), r= x(); assert(p == q == r);
![Page 33: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/33.jpg)
Auto-Gen Boilerplate
• @autoc{onstruc}tor, @autostring, @autoequals, @autocompare, @autosuper, @autoall
• Autosuper clones all superclass constructors• Autoctor creates constructors for fields• Autostring creates {human|debug}toString(), • Autoequals creates equals() & hashCode()• Autocompare adds Comparable/creates compareTo()• Depend on @forctor, @fortostring, @forequals, etc.
– Ex. @autoall class C extends Q { @property int x, y, z; }• @property fields– Ex. @property(vetoable=true) String name;– Creates missing accessors and event notifications
![Page 34: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/34.jpg)
Auto-Gen Boilerplate
• @struct classes– Ex. @struct class Person { String name; int age; }
• static top-level classes– Ex. static class Utils { int func1() { .. }; … }
• @delegateto fields– Ex. interface Y { void f2(); void f3(); }
class X implements Y { void f1() {… }; void f2() { … } } class A { @delegatesTo X x; void f3() { … } }
– A has f1(), f2(), f3() }; A implements Y
![Page 35: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/35.jpg)
Ease-of-Use
• Simplified “Field” references– Ex. anAddress.city anAddress.getCity()– Ex. anAddress.city = “” anAddress.setCity(“”)
• Named Map keys– Ex. aMap[“xxx”] aMap.get(“xxx”) or (maybe)– Ex. aMap.xxx aMap.get(“xxx”)– Ex. aMap.”a string” aMap.get(“a string”)
![Page 36: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/36.jpg)
JRE Extensions
• Fluid Setters on all JRE classes– Ex. X x = new X().xxx(1).yyy(2).zzz(3);
• Add large number of high use utility methods– Ex. see teasers for example– Minimize need for adding OSS for common tasks– Fix many JRE self inconsistencies
• Compile time – Class.getCompileTime()– Ex. var builtAt = new Date(
Main.class.getCompileTime());
![Page 37: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/37.jpg)
Misc
• Broaden string usage via Stringy ** interface– All CharSequence used where String used today– Retrofit String Stingy declarations in JRE
• Defaulted Expressions– Ex. Integer.parseInt(“bad value”) default -1;
• @partial classes– 1+ source file per class– Ex. see teasers for examples
• Package literals– Ex. var utils = java.util.package;** Stringy extends CharSequence
![Page 38: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/38.jpg)
“C” Style Conditional Code
• @conditional (excludable) methods– Ex. see teasers for examples
• #section <desc>/#endsection– Ex. see teasers for examples
• #if/#else/#elif/#endif– Ex. see teasers for examples
• #include sourceFile **– Add source text verbatim (alt for partial classes)
** could be tricky for IDE to implement; Listings may be needed
![Page 39: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/39.jpg)
Questions?
![Page 40: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/40.jpg)
TEASERS (VIA EXAMPLES)
![Page 41: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/41.jpg)
Operator Overloading
• Allow most operators on any reference type– as normal instance methods; compiler maps
operator to associated method call– Left is instance: (ex. $plus, $or, …) – Right is instance: (ex. $iplus, $ior, …)– Augmented ?=, ++, --: ($aplus, $aor, …) – ==, != require enablement (via annotation)– >, >=, <, <= if type T is Comparable<T>
![Page 42: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/42.jpg)
Operator Overloading…
• Supported Operators– + - * / \ % ** ++ -- & | ^ ~ < <= > >= == != ?= >> >>> << <<< [] []= () :: ==> <== ... >.. ..< :x x: (x is + - * / \ % & | ~ ^ < >)
• Ex. Using type Color– Color r, g, b, x = r + 2 * g + ++b; – Color x = r.$plus(g.$imult(2)).$plus(b.$pinc());
implies new operator; italics implies new capability
![Page 43: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/43.jpg)
Operator Overloading…
• Enhanced conversions1. If target type has constructor taking source type2. If target type has static “from” or “fromXxx”
method taking Xxx source type• Convert when
1. Upon explicit cast: Date d; d = (Date)aCalendar; 2. Upon initialization: Date d = aCalendar;3. Assignment/comparison between Number types
![Page 44: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/44.jpg)
Op Overloading - Strings
• Examples: String x, y, z– x = y.concat(z); (or special compiler case x = y+z)– x = y.repeat(3); (new, dup 3 times)– x = y.repeat(-3); (new, reverse dup 3 times)
• Vs.– x = y + z; (can drop special compiler support)– x = y * 3; x = 3 * y;– x = y * -3; x = -3 * y;
![Page 45: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/45.jpg)
Op Overloading - Numbers
• Examples: BigInteger bi1 = ..., bi2 = …; AtomicInteger a2 = …;– BigInteger bi3 = bi1.add(bi2);– a2.addAndGet(3);– int x = a2.incrementAndGet();
• Vs:– BigInteger bi3 = bi1 + bi2;– a2 += 3;– int x = ++a2;
![Page 46: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/46.jpg)
Op Overloading - Numbers
• Examples:– long fac(long x) {
if(x < 0) throw new IllegalArgumentException(); if(x == 0) return 1; return x * fac(x – 1);}
•}Vs:– long fac(long x) {
if(x < 0) // auto promote to 0L throw new IllegalArgumentException(); if(x == 0) return 1; // auto promote to 1L return x * fac(x - 1);}
![Page 47: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/47.jpg)
Op Overloading - Numbers
• Examples:– BigInteger fac(BigInteger x) {
int rel = x.compareTo(BigInteger.ZERO); if(rel < 0) throw new IllegalArgumentException(); if(rel == 0) return new BigInteger.ONE; return x.multiply(fac(x.subtract(BigInteger.ONE));}
•}Vs:– BigInteger fac(BigInteger x) {
if(x < 0) // auto promote to 0X throw new IllegalArgumentException(); if(x == 0) return 1; // auto promote to 1X return x * fac(x - 1);}
![Page 48: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/48.jpg)
Op Overloading - Collections
• Examples: List<String> ls2 = …, ls2 = …;– List<String> ls3 = new ...;– ls3.addAll(ls1);– ls3.addAll(ls2);
• Vs:– List<String> ls3 = ls1 + ls2;
![Page 49: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/49.jpg)
Op Overloading – Collections…
• Examples: List<Integer> li1 = ..., li2 = ...: – i1.add(1); li1.add(2); li1.add(3);– li1.addAll(li2);
• Vs:– li1 << 1 << 2 << 3;– li1 << li2;
![Page 50: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/50.jpg)
Op Overloading – Collections…
• Examples: List<integer> li1 = …; Map<String,String> mss1 = ...;– li1.set(2, li1.get(3));– String s = mss1.get("hello");– mss1.put("hello", "goodbye");
• Vs.– li1[2] = li1[3];– String s = mms1["hello"];– mms1["hello"] = "goodbye";
![Page 51: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/51.jpg)
Op Overloading - Streams
• Examples: StringBuilder sb = ...;– sb.append("Hello").append(" ").
append("World!"). append(‘\n’);• Vs.– sb << "Hello" << " " << "World!" << '\n';– Also:– PrintWriter pw = ...;
pw << "Hello" << " " << "World!" << '\n';
![Page 52: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/52.jpg)
Op Overloading - Calls
• Examples: – import static System.out;– out.printf("Hello %s!%n", user);– out.print(String.format("Hello %s!%n", user));
• Vs.– out("Hello %s!%n", user);– out.print("Hello %s!%n"(user));
![Page 53: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/53.jpg)
Op Overloading - Much Potential
• Example: Possible CharSequence (covers all implementations) overloaded operators– Compile RE: ~”...”; Match RE: “…” ~= “…”;– Concat: “…”+”…”; – Repeat: “…”*n (reverse if <0); “…”*0 == “”– Remove: “….”-”…”– Substring: “…”[x..<y]; CharAt: “...”[n]– Replace: “…”[m...n] = “…” (remove if “”)– Append: “…”<<“…”; Prepend: “…”>>“…”;
• Above tip of iceberg
![Page 54: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/54.jpg)
Declaration Type Inference
• Java supports right-side generics inference today– Map<String, Integer> x = new HashMap<>();
• Add left-side inference• Map<> x = new HashMap<String, Integer>();
• Generics on either side should be sufficient• Example:– Map<> snmap = { "one":1, "two":2, "three":3.0 };– Is interpreted as:– Map<String, ? extends Number> snmap = – { "one":1, "two":2, "three":3.0 };
![Page 55: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/55.jpg)
Var Type
• Individual declarations:– Integer ten = new Integer(10);– int twenty = 20; – long ninety = 90; – String name = "Barry“;– double y = 30.5;– LinkedList<> stringList1 = new LinkedList<String>();– Number x = new Integer(20); – List<String> stringList2 = new LinkedList<String>();
![Page 56: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/56.jpg)
Var Type…
• Can become simplier:– var ten = new Integer(10),
twenty = 20, ninety = 90L, name = "Barry“, y = 30.5, stringList1 = new LinkedList<String>();
– Number x = new Integer(20); – List<String> stringList2 = new LinkedList<String>();
Consider using VAR that makes primitive into wrapper type.Unlike in JavaScript var type is static per identifier
![Page 57: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/57.jpg)
Collection Initialization
• Arrays support initialization:– Example:• new Object[] { 1, 2, 3 }
• Collections should also:– Examples:• new ArrayList() { 1, 2, 3 };• new HashMap() { 1:”one”, 2:”two”, 3:”three” };
Collection implements new interface: Initable<T> with initAll(T[]|Collection<T>)
![Page 58: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/58.jpg)
Immutable Tuple Type
• Examples:• (); (1,) // empty; 1 Integer • (1,2,3.0) or (1,2,3.0,) // 3 Numbers• ("hello", "World!") // 2 Strings• (1, "World!") // 2 Objects• ((1,2),('a','z')) // 2 Tuple<? extends Object>• (var x, var y, var z) = (1, 2.0, “Three”)
Syntax possibly: #( <value>,…) Not fixed size so therefore non Generic; like immutable ArrayList
![Page 59: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/59.jpg)
Immutable List Type
• Examples:– List<Integer> li = 1::(2::(3::(4::Lists.Nil))));– List<?> lx = 1::(2.0::(”Three”::
((4::Lists.Nil)::(”Five”::Lists.Nil))::Lists.Nil));
“::” for example, other operators possible: ex. +:, :+, \+Note: if “::” right-assocative then List<Integer> li = 1::2::3::4::Lists.Nil;
![Page 60: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/60.jpg)
Immutable Map Type
• Like standard Map interface except:– put() & putAll() return the Map instance• Recommend putAll over put for multiple values
– remove() returns the Map instance• Implementations– Optimize update/replacement• In general only hash bucket lists need to be changed
![Page 61: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/61.jpg)
Immutable Range Type
• Examples:– 0 to 9: 0 ..< 10 (or 0..<10…1); 9 to 0: 10>..0…-1– 0 to 10: 0 … 10; 10 to 0: 10…0…-1– Odds: 1…100...1; Evens: 0…100…1– Calc steps : 1…Long.MAX_LONG…(x -> x * x)– Characters: ‘a’…’z’ (‘a’, ‘b’, … ‘y’, ‘z’)– Strings: “aa”…”zz” (“aa”, “ab”, … “zy”, “zz”)– Empty: 0..<0 (many other alternatives,
Ranges.EMPTY)
![Page 62: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/62.jpg)
Immutable Range Type…
• Examples:– Over array: Ranges.make(new int[] {1,2,3})– Or: Ranges.make(1,2,3);– Over collection: Ranges.make(aList)– Or: aList.asRange() (takes static snapshot)– Variable, non int: double x, y, z: x…y…z– assert 1..100 < 1…1000– assert 1…100…1 > 1…100…2
Assume “==“ overloaded to equals(); < to compareTo()
![Page 63: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/63.jpg)
Immutable Range Type…
• Examples:– for(int i: 0..<100) { :}
– for(1…n) { :}If index not needed
Assume “==“ overloaded to equals(); < to compareTo()Enhanced for syntax
![Page 64: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/64.jpg)
Range as Index
• Examples:– “0123456789”[1…3] == “123”– “0123456789”[-1…-3] == “987”– “0123456789”[-3…-1] == “789”
Assume “==“ overloaded to equals(); “[]“ overloaded
![Page 65: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/65.jpg)
Immutable Rational Type
• Examples:– int x = 1, y = 2, z = 20, a = 21, b = 11, zero=0,
num1 = 21:/5, num2 = 5:/3; – Rational r1 = x:/y; // 1:/2 (also 1 :/ 2)– Rational r2 = z:/y; // 10:/1– Rational r3 = (2*x):/-y; // -1:/1 ==
-Rationals.ONE– Rational r4 = (50*-y):/z; // -5/1– Rational r5 = a:/b; // 21:/11
Consider adding (long) rational primitive type ; compiler only (2 int/long) – no JVM change
Note: Could use \ instead of :/ for rational divide
![Page 66: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/66.jpg)
Immutable Rational Type…
• Examples:– Rational r6 = x:/zero; // DivideByZeroException– Rational r7 = zero:/x; // 0:/1 == Rationals.ZERO– Rational r8 = num * -num2; // -21:/3– Rational r9 = 1:/num1; // 5:/21– Rational r10 = 1:/r7; // gets
DivideByZeroExceptionRational
– int ix = (int)(r1 + r2 * r4); // -25:/1 -25
![Page 67: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/67.jpg)
Immutable Complex Type
• Examples:– assert 1j.equals(1i); // literals wrapped first– Complex c1 = 1; (or 1+0i)– Complex c2 = -2j; (or 0-2j or 0+-2j)– Complex c3 = 1+2i; – Complex c4 = 1-3e7i;
Consider adding complex primitive type; compiler only (2 doubles) – no JVM changeImportant for spaces reasons in matrices
![Page 68: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/68.jpg)
Immutable Complex Type…
• Examples:– Complex c5 = 1.0+2dj;– Complex c6 = 1.0b+-0.1j; (or 1.0b-0.1j)– Complex c7 = 1+i; // illegal (unless: Complex i = 1j)– Complex c8 =
![Page 69: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/69.jpg)
Immutable UnitValue Type
• Prevent Apples + Oranges errors• Units define “units” (ex. Newton, Hertz, Gram)– Custom or JRE provided
• UnitValues are Numbers with an associated Unit– Ex. IntegerUnitValue extends Integer **– Can +,- only compatible– Can *,/,** any
Requires non-final Integer or new nonpackagefinal
![Page 70: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/70.jpg)
Immutable UnitValue Type…
• Examples:– Unit newton = ...; meter = ...; second = ...; – UnitValue newton100 = 100 * newton;– Integer newton100asInteger = newton100;– Integer unitVelocity = 1 * (meter / second);– UnitValue m = 1000 * gram;– UnitValue e = m * C ** 2; // or = m * C * C;– UnitValue x = 1000 * second;– Number y = e + x; // Exception– Number z = e * x; // OK
![Page 71: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/71.jpg)
Packed Matrix Type
• 3-dimensional [N, M, L] Matrix example– N * M * L cells
• View on Matrix• View on View• Can also view as
array(1 dimensionN * M * L long)
• Can update through view
• Bit, primitive, refIgnore labels
From http://www.altera.com/technology/system-design/articles/2013/scanned-radar-signal-processing.html
![Page 72: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/72.jpg)
Matrix Access
• Whole Matrix and View (AKA sub-range)• Picture shows
possible additional options(stride, selection,partition, etc.)
• Do provide transformslike flip and transpose
http://incanter.org/docs/parallelcolt/api/cern/colt/matrix/doc-files/slice.gif
![Page 73: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/73.jpg)
Potential Functionality
• Get and set the cell @ index• Get rank and shape• Apply Math.* operations to all elements using lambdas• Operations to transpose, inverse, etc. • For liked shaped:
– Standard operations (ex. +, -, *, /)– CompareTo elements (produce array of ints)
• Reduction functions (sum, min/max value, etc.) using lambdas• (Consider) array construction functions (merge, pack, spread,
unpack)• Parallel operation variants where no cross-cell contention
![Page 74: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/74.jpg)
Checked Arithmetic
• Examples: All generate exceptionsassume all in @checked(overflow=true, underflow=true) method– int x = 1; x << 50 - overflow (needs BigInteger)– Int x = 1024 >> 10 - underflow (result is double)– Int x = 0x7FFFFFFF + 1 – overflow (sign change)– int x = (int)1FFFFFFFFL – overflow (sig bits lost)– Short s = (short)(65 * 1024) - ditto
![Page 75: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/75.jpg)
Literals for all Number Types
• Add More literals:– BigInteger: 100000…0000000X (or x)– BigDecimal: 100000000000.00000B (or b)
• Allow “_” between digits• Some types have constant expressions instead
of literals– Rational type: 1 :/ 2– Complex type: 10+3j; 10 @ Math.PI / 2
![Page 76: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/76.jpg)
Power Operator
• Allow xy to be expressed as an operator (vs. function) x ** y – New right-associative binary “**” (AKA
$power/$starstar ) operator• Add similar Java/JRE support as * (multiply)
has; on all numeric types (primitive and Big)• Example:– long x = 2**45; double y = Math.PI**-3.5**2
Assume “**” overloaded; Suggest creating BigMath class like Math class
![Page 77: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/77.jpg)
“As” Type Testing
• Example:• String s = “…”; Object o = new Integer(5);• assert as(String.class, s) == s;• assert as(Integer.class, s) == null;• assert as(Integer.TYPE, s) == null;• assert as(Integer[].class, o) == o;• as(Integer[].class, o, n -> System.out.printf( “%d%n”, n[0]) );
static <T> Object.as(T type, Object v, { lambda })Interface Castable<T>; T castTo(Class<T>)
![Page 78: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/78.jpg)
Safe Dereference Operator
• Shorten common Java idiom– x != null ? x.y : null
• Can cascade: (ex. x.?y.?z)• Ex.– String city= user?.address.?city
• Vs: – String city = (user != null ?(user.address != null ?
(user.address.city) : null) : null)• Add @autosafe class/method annotation– Converts use of “.” to “.?”
![Page 79: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/79.jpg)
Default Operator
• Shorten common Java idiom– x ? x : y;
• Default (Elvis): x ?: y– Short for: isTrue(x) ? x : y – Uses Java truth (!null, !0, !false); returns x if It is “true”,
else y• Add HasTruth interface for reference types– If implemented; use its isTrue() method**– Ex. String.isTrue() = length() > 0;– Ex. Integer.isTrue() = intValue() != 0;
**: Operators && and || also do this
![Page 80: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/80.jpg)
Import Aliases
• Examples: – import java.sql.SQLException as SqlException– import java.util.List as ValueList– import java.awt.List as SelectList– import javax.swing.JButton as Button– import SomeInterface as ISomeInterface– import SomeInterfaceImpl as SomeInterface– import static Math.sin add sine
![Page 81: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/81.jpg)
Terse Imports
• Examples:– import java.swing. JTable:JPanel:JButton– import java.swing. JTable as Table:
JPanel as Panel, Pane: JButton as Button– import javax.swing.J* as *– import xxx.yyy.I?*Service as ?*Service
![Page 82: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/82.jpg)
Package Imports
• Examples:– import java.awt as awt– import java.util as u
assert java.util.package == u.packagethen
– u.List items = new u.ArrayList()– awt.List select = new awt.List()
![Page 83: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/83.jpg)
Import Blocks
• Examples:– void xxx() { import javax.swing.*; :}
– void xxx() { import javax.swing.* { : }}
![Page 84: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/84.jpg)
Type Aliases
• Examples:– typealias java.util.StringBuilder as SB
assert StringBuilder.class == SB.class– typealias String as string– typealias String[] as strings– typealias java.math.BigDecimal as decimal– Typealias boolean as bool– typealias java.sql.SQLException as SqlException– typealias HashMap<? Extends CharSequence, ?
Extends CharSequence> as SeqToSeqMap
![Page 85: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/85.jpg)
Method Aliases
• Examples:– methodalias String.toString(void) as asString– methodalias String.length(void) as size– methodalias StringBuilder.getLength(void) as size– methodalias StringBuilder.append(…) as add– methodalias <K extends String, V extends
Number> Map<K, V>.put(K, V) as putNumber
![Page 86: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/86.jpg)
Field “Aliases” by Annotation
• Leverage JavaBeans• Auto-generation of access methods• @alias(“x, y, z”) private int xxx– Perhaps @alias(“x, y, z, xxx”) private int _xxx
![Page 87: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/87.jpg)
Method “Aliases” by Annotation
• Auto-generation of methods• Visibility same as base method• @alias(“pqr, lmn”) public int xyz() { … }• @Deprecated only effects base method
![Page 88: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/88.jpg)
Map/List Literals
• Java has array literals, it needs to add literals for common collections
• List literal: [ <value>,… ]• Map Literal : { <key>:<value>, … }• Type is least common sub-type of key/value• Literals can be passed to constructors to set
type (or cast to type)– new ArrayList([1,2,3]) or (TreeMap){1:x,2:y,3:z}
May need to use #[…] and #{…} format
![Page 89: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/89.jpg)
Literal Extensions
• Examples:– Class: String.class (already supported)– Package: javax.swing.package– Field: JComponent.@name– Method: String.substring(int, int)
![Page 90: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/90.jpg)
Method Bindings
• Example:– String s = ...;
Binding** substring = Bindings.bind(String.substring(int, int), s);-- or – Binding substring = String.substring(int, int)::s;
:String s2 = substring(0, 10);
** an interface with at least one implementation
![Page 91: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/91.jpg)
Method Bindings…
• Example:– MyIOService s = …;var copy = MyIOService. copyTree(File, File)::s…new File(“.”)…new File(“elsewhere”).async(true);
– var f = copy();
: do other stuff
int rc = f.get();
Call operatorSame as copy.$call()
![Page 92: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/92.jpg)
Add “Chaining” Setter
• For field “<type> xxx” JavaBeans defines access methods as:– <type> get/isXxx() { return xxx; }– void setXxx(<type> v) { xxx = v; }
• Add new setter:– <thisType> xxx(<type> v) { xxx = v; return this; }
• This allows “fluent” assignments like:– Xxx xxx = new Xxx().aaa(1).bbb(3).ccc(3);
• Retrofit into all JRE classes
![Page 93: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/93.jpg)
Pseudo Instance Methods
• Examples:– Class X has no doThis/doThat methods
• These calls:• X x = new …• x.doThis(1, 2, 3)• x.doThat(3, 2, 1)
• Becomes:• SomeUtilClass.doThis(x, 1, 2, 3)• SomeUtilClass.doThat(x, 3, 2, 1)
Must be unique match across imported (vs. all) classes; else need marker annotation on subject methods
![Page 94: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/94.jpg)
Pseudo Instance Methods…
• Examples: Based on String class• This call (previously invalid):
– String x = “%s %s %s”.format(“x”, “y” “z”);
• Now succeeds (is mapped to):• String x =
String.format(“% s %s %s”, “x”, “y” “z”);
• Only if no real instance method matching format(…)
![Page 95: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/95.jpg)
Pseudo Methods
• Assume class Expando implements (new) SupportsPseudoMethods** interface
• Assume Expando class has methods:– normalMethod1(), normalMethod2() and
onMethodCall()• onMethodCall has cases for:– nowDate(), nowMillis() and other()
** suggest better name
![Page 96: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/96.jpg)
Pseudo Methods…
• Example:– Expando e = new Expando();// only real methode.normalMethod1(); // called via redirectionDate d = (Date)e.nowDate(); long seconds = (Long)e.nowMillis();e.other();e.xxx();
• All the above statements compile, but the xxx() call fails at run time with a MethodNotFound-Exception.
![Page 97: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/97.jpg)
Dynamic Variables
• Examples:– @dynamic Object duck = new Duck();– duck.quack();– double weight = (Double)duck.getWeight();
• Compiles OK; quack() and getWeight() work if defined in Duck (or superclass), else runtime MethodNotFoundException occurs
Simple implementation uses reflection; better invokedynamic
![Page 98: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/98.jpg)
String Enhancements
• Simple (JavaIdCharacter content only): `this_is_a_string (makes great hash key)
• Long Strings: “”” any text here, including “ and ‘ and \n and line ends until the next “””
• Raw Strings (ignore ‘\’ as escape):– “this \n is not an escape”R (or r)– Also “”” … “””r
![Page 99: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/99.jpg)
String Enhancements…
• Smart Strings: ~“””${name} is ${age > 50 ? ”old” : “young” }””” **– Simple id reference can be shortened: $name
• Causes any ${<expr>} to be replaced by the value of the <expr> evaluated in current context – May cause internal Map to be sent to interpolate()
with all (perhaps just referenced in expr) variables in current context.
**: overloaded operator does “interpolate()” (ah la Perl/Groovy) behavior
![Page 100: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/100.jpg)
String Enhancements…
• Unified StringBuilder/Buffer and String– Create new Interface Stringy that covers all String
instance methods– Make StringBuilder/Buffer implement Stringy• So they can be used most places Strings are• Replace most JRE methods String parameters/results
with Stringy type
– The compiler will treat Stringy items as String (ex. x + y)
Stringy extends CharSequence
![Page 101: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/101.jpg)
Defaulted Positional Parameters
• Ex. public int xxx(int a, int b = 2, long c = 3) { … }• Generates methods:– public int xxx(int a, int b, long c) { … }– public int xxx(int a, int b) { return xxx(a, b, 3); }– public int xxx(int a) { return xxx(a, 2, 3); }
• Cannot combine with … parameters• Fails if ambiguous methods generated• Allows: public int xxx(int a, var b = 2, var c = 3L) …
Distinct overloaded methods; not call site injection
![Page 102: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/102.jpg)
“Keyword” Parameters
• Example:– // Xxx(Map<String,Integer> params)– Xxx xxx = new Xxx({"x":1, "y":2, "z":3}); or just– Xxx xxx = new Xxx("x":1, "y":2, "z":3);
• More generally:– // Xxx(int x, int y, Map<String,Integer> params)– Xxx xxx = new Xxx(1, 5, `x: 1, `y: 2, `z: 3); key order not– Xxx xxx = new Xxx(1, `x: 1, `y: 2, `z: 3, 5); important– Xxx xxx = new Xxx(`z: 3, `y: 2, `x: 1, 1, 5);
• If the key consists only of Java Id– Xxx xxx = new Xxx(z: 3, 1, y: 2, x: 1, 5); no quoting needed– Xxx xxx = new Xxx(z: 3, 1, (y): 2, x: 1, 5); fails, must be const
Only works if last parameter is Map<String,?>
![Page 103: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/103.jpg)
Reference Parameters
• Given:public <T> static void swap( @ref T a, @ref T b) { T t = a; a = b; b = t;}
• Ex: @ref int v1 = 3**, v2 = 5; : swap(v1, v2); assert v1 == 5 && v2 == 3;
** could be internally: Wrapper<Integer> v1 = new Wrapper(3), …
![Page 104: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/104.jpg)
Specialized toString
• Add debugToSting() & humanToString()• Ex:
public String debugToString() { StringBuilder sb = new ..; $debugPrefix(sb); getClass.getName $debugBodyStart(sb); “[“ $debugBody(sb); “” $debugBodyEnd(sb); “]” $debugSuffix(sb); “@”+System._HashCode return sb.toString();}
• Allows subclasses opportunity to override minimally (ex. override $debugBody() only)
toString() can call either or neither at its discretion; Object.toString() { return debugToString(); }
![Page 105: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/105.jpg)
Enhanced Switch
• Allow “goto” case instead of break • Class z = new ….;switch(z) { case String.class: : break; case Xxxx.class: case Number.class: : goto String.class;}
Consider “select” statement; same as “switch” with auto “break” between cases.Consider allowing syntax: case x, y, z:
![Page 106: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/106.jpg)
Enhanced Switch…
• Add new interface Case with methodboolean matches(Object other)
• Switch can test any type implementing Case– Use if/else If/else implementation– Implement Case on (at least) any JRE Comparable class and
enums– Consider adding Object method matches() so all types can be
used in switch (thus no Case interface needed); defaults to calling equals()
• Can eliminate special String/enum support• More readable than if/else if/else sequences
![Page 107: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/107.jpg)
Enhanced Switch…
• Example:• Class z = new ….;switch(z) { case String.class: : break; case Xxxx.class: case Number.class: : break; :}
![Page 108: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/108.jpg)
Appendable Ehnancements
• Make Appendable more like PrintStreams– default Appendable appendln(CharSequence cs) { append(cs); append(‘\n’); return this;}
– default Appendable appendf(String fmt, Object…va) { append(String.format(fmt, va); return this;}
![Page 109: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/109.jpg)
Get Compile Time
• Add Class method: long getCompileTime()– Milliseconds since epoch
• Allows build time to be easily accessed– Avoid class path walking, etc.
![Page 110: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/110.jpg)
Basic JSON Support
• Example:• String t = “““{x**: 100, y: 1, z:”Hello!”}”””;JsonObject jo = JsonObject.parseJson(t);System.out.printf( “Value of x=%d”, jo[`x]);jo[`a] = “World!”; // adds “a”
**: allow unquoted keys if only JavaIdJsonObject implements Map<String,?>; ? Restricted to null, String, Number, JsonObject, List<JsonObject>
![Page 111: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/111.jpg)
Basic XML Support
• Example:• String t = “““<xxx x=‘1’ y=‘2’ z = ‘3’> <i>body text</i></xxx>”””;XmlElement xxx = XmlElement.parseXml(t);System.out.printf( “Value of xxx.y=%s”, xxx[`y]);xxx << (new XmlElement(“zzz”) << new XmlTextNode(“…”));
XmlElement implements Map<String,String>; has List<XmlElement>
![Page 112: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/112.jpg)
Pseudo Implements
• Ex.• interface ABC { void a(); void b(); void c(); }
• @implicitinterface(ABC.class) class XYZ { public void a() { … } public void b() { … } public void c() { … } void others() { … }}
• XYZ implicitly conformsTo(ABC.class)
![Page 113: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/113.jpg)
Pseudo Implements…
• Elsewhereclass LMN { void doIt( @implicitinterface ABC abc) { abc.b(); }}
• Any class that conformsTo(ABC) can be passed as a valid argument (such as XYZ)
![Page 114: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/114.jpg)
Partial Classes
• Example: in Xxxx.java@partial public class Xxxx { @property int x, y, z;}
• Example: in Xxxx-partial1.java@partial class Xxxx { public int sum() { return x + y + z; }}
All parts must be in same package (i.e., directory)
![Page 115: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/115.jpg)
Partial Classes…
• Acts like: in Xxxx.javapublic class Xxxx { @property int x, y, z; public int sum() { return x + y + z; }}
![Page 116: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/116.jpg)
Conditional Methods
• Example.@conditional( name=DEBUG, value=true) public static void trace( String format, Object… args){ .. }
• Usagetrace(“This call (and parameters)” + “ may not be compiled: %s”, “” + “ “ + … “”);
• Compiler Trigger: (say) -cond:DEBUG=false
![Page 117: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/117.jpg)
Source Sections
• Add #section <name>/#endsection pre-processor statements
• Used to mark source as a section– Document purpose for range of source lines– IDE can easily show/hide sections; direct navigation– Nesting allowed
• Ex.#section Public Classes :#endsection
![Page 118: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/118.jpg)
Conditional Source
• Add #if <cond>/#else/#elif <cond>/#endif pre-processor statements– Tests debug symbols (missing symbol implies false)– <cond> : boolean expression of id, ==,!=, >, >=, <, <=, &&,
||, !, (,)– Id set from command line; boolean/int/String only
• Compiler Trigger: (say) -D:DEBUG=false;LEVEL=11• Ex:
#if DEBUG && LEVEL<10:#endif
![Page 119: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/119.jpg)
Duplicate Methods in Interface
• Given: interface X { void x(); void a(); }interface Y { void y(); void a(); }interface Z { void z(); void a(); }
• If used:class A implements X, Y, Z { … }
• There are up to three a() methods to define
Some under the covers name mangling may be used, ex. X.a() a$X()
![Page 120: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/120.jpg)
Duplicate Methods in Interface…
• Client Example:class C { A a = new …; public void xxx() { a.x(); a.a(); // call new a() def’n a.X.a(); // call X.a() def’n or ((X)a).a(); : }}
![Page 121: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/121.jpg)
Parallel For
• Example:AtomicLong sum = new …;Map<String, ?> options = …;parallelFor(var ti: (0,1000)..<(0,2000); options) {
(int x, int y) = ti; sum += x * y;}
![Page 122: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/122.jpg)
Actor Parallel Execution Model
![Page 123: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/123.jpg)
Actors Implementation
• Managers own 0+ Actors• Managers manage
0+ Threads• Actors buffer
0+ Messages• Managers send
messages to Actors• Actors use Threads to
process messages
Manager Actor
Message
*
*
Thread* Per Message
![Page 124: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/124.jpg)
Services
• Example:• In System Code:– class MyService implements
MyInterface, Service {...} : Registry registry = System.getSystemRegistry(); MyService ms = new MyService(); Object id = registry.register(ms, "MyInterface1", new ServiceDescriptor(MyInterface.class, "1.5")); registry.setValue(id, "test", "xxx");
![Page 125: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/125.jpg)
Services…
• Example:• In client Code:– Registry registry = System.getSystemRegistry();
try (var sh = registry. getRequiredService(MyInterface.class)) { MyInterface mi = sh.resolveService(); : // do something with mi : } catch(...) { ... }
Note: each use of this code could get a different implementation class
![Page 126: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/126.jpg)
Service Dependency Injection
• Example (In some class):• @inject(name=“datasource1”, deferredOk=false)
@property DataSource ds;– Uses getRequiredService(DataSource.class,
“datasource1”)• @inject(path=“\xxx”, name=“anXxx”)
@property Xxx xxx;– Uses getService(Registry.class, “xxx”).?
getService(Xxx.class, “anXxx”)– If null; setup listener to set when defined
![Page 127: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/127.jpg)
Utility Libraries
• Raise the bar (significantly) on the support standalone JRE can provide– Standardize behavior; extend closed classes– Many sites want to constrain adding OSS
• Add utility methods/classes from popular Open Source Projects– Survey popular; ex. Apache, Google, SourceForge– List TBD (and growing per Java release)– Likely add many 100s of methods (fewer classes)– Generally small (<100 LOC) and well tested in wild
Cost/Importance varies with scope/quantity of included libraries
![Page 128: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/128.jpg)
Utility Libraries…
• Example of one such method: safe equality• Add public static Object method:boolean isEqual(Object l, Object r) { if(l == null) return r == null; else return r == null ? false: l.equals(r);}
![Page 129: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/129.jpg)
Utility Libraries…
• Example of one such method: consistent code– Allows same syntax primitive or reference types– No automatic conversion of primitive to wrapper• But cast allowed: isEquals((Integer)1, (Number)2)
• Add public static Object methods:boolean isEqual( <prim>** l, <prim> r) { return l == r;}
** any primitive type
![Page 130: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/130.jpg)
Property Definition
• Add @property field** annotation• Causes automatic access method generation– Unless programmer defined
• Supports simple, 1-dim array and generic types
**: allowed in both class (bodies provide) and interface
![Page 131: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/131.jpg)
Property Definition…
• Values: – observable|vetoable=true|false• Auto-generate add/removeListener• Auto-generate fireListeners
– visibility: control access method visibility• (public visibilities) rw(default), ro, wo; private
– name: alternate name (vs. field) to name the property
**: allowed in both class (bodies provide) and interface
![Page 132: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/132.jpg)
Property Definition…
• Example (in class X):– @property(vetoable=true) String ssn;
• Generates code similar to this:– private String _ssn;– @const public String getSsn() { return _ssn; }
![Page 133: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/133.jpg)
Property Definition…
• Example (continued):– protected void _firePropertyChangeListeners( PropertyChangeEvent e) { // walk listeners with callback}
– Listener may/may not throw VetoException– More complex (ex. indexed) properties may have
more get/set methods
![Page 134: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/134.jpg)
Property Definition…
• Example (continued):– private List<PropertyChangelistener> _listeners = …; **
– public void addPropertyChangelistener( PropertyChangelistener l) { … } **
– public void removePropertyChangelistener( PropertyChangelistener l) { … } **
**: only on topmost class needing this
![Page 135: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/135.jpg)
Property Definition…
• Example (continued):– public void setSsn(String ssn) { try { _firePropertyChangeListener( new PropertyChangeEvent( this, “ssn”, _ssn, ssn); _ssn = ssn; } catch (VetoException e) {}; }
– public X ssn(String ssn) { setSsn(ssn); return this; }
![Page 136: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/136.jpg)
Direct Property Access
• Implied use of get/set methods • Example:– class X { @property int a, b, c; public void xxx() { a = b + c; }}
– In other classX x = new x();int z = x.a + x.b + x.c;
Becomes getC()
Only use get/set if field not visible (ex. private int a)
![Page 137: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/137.jpg)
Direct Map Key Reference
– Example:• Given:
Map<String, String> map = …;• Then:
map.name = map.first + ‘ ‘ + map.last;• Equivalent:
map.put(“name”, map.get(“first”) + ‘ ‘ + map.get(“last”));• Also:
map.”has \n blank”r = “…”;• Complex expressions must use [ … ]:
map[map.first + ‘ ‘ + map.last] = “new”;
Map implements new AutoGetPut<T> interface – get(String), put(String, T)
![Page 138: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/138.jpg)
JavaScript-like Objects
– Given: var map = { name:“Barry”, ucase:{ String s -> return s.toUpperCase(); } };
– Then:String uc = map[`ucase](“hello” + map.name);
– Or:– String uc = map.ucase(“hello” + map.name)
![Page 139: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/139.jpg)
Extended Auto-Boxing
• On any use of a primitive expression if followed by dereference operator (“.”, “.?”) and a method call then auto-box the primitive and apply the method to the wrapped value.
• Add utility methods to all wrapper types– Ex: Integer.upTo(int max, Lambda)
1.upTo(10, x -> System.out.println(x)); **– Java.lang.Math functions– Etc.
**: Also can achieve as: 1..<10.each(x -> System.out.println(x));
![Page 140: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/140.jpg)
Simplified Default Processing
• Exampleint rc = Integer.parseInt(s) default 0;
• If s is “55”; rc == 55• If s = “bad value”; rc == 0
![Page 141: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/141.jpg)
Delegate Fields
• Example:– Given: class X { public static final int A = 1; void a(); void b(); void c();}
– Given: class Y { public static final int Z = 1; void x(); void y(); void z();}
![Page 142: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/142.jpg)
Delegate Fields…
• Example:– Given: class Z { @delegateto @property X x; @delegateto @property Y y void a() { … } void b() { … } void z() { … }}
![Page 143: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/143.jpg)
Delegate Fields…• Example:
– Generates: class Z implements X, Y { public static final int A = 1; public static final int B = 1; private X _x; private Y _y; void a() { … } void b() { … } void c() { _x.c(); } void x() { _y.x(); } void y() { _y.y(); } void z() { … } }
![Page 144: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/144.jpg)
Auto-generate common methods
• Example@autoconstructors @autoequals @autostring @autocompareto class X implements Compareable { @forall @property String name; @forall @property int age;}
![Page 145: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/145.jpg)
Auto-generate Constructors
• Allow addition of parameter:– @auto value used as parameter value
• @auto(4) public Xxx(int a, int b, String s, Thread t);
• Generates:public Xxx(int a, int b, String s, Thread t) { this(a, b, s, t, 4);}
![Page 146: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/146.jpg)
Auto-generate Constructor…
• Which allows:• @auto(-1) public Xxx(int a);• @auto(“”) public Xxx(int a, int b);• @auto(null) public Xxx(int a, int b, String s);• @auto(4) public Xxx(int a, int b, String s,
Thread t);• @auto public Xxx(int a, int b, String s,
Thread t, int size); **
** parameter name must be same as field name
![Page 147: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/147.jpg)
Struct Classes
• Many class are data-only (have little/no behavior) so make them easier to create
• Add @struct class annotation– @autotostring, @autoconstructors, @autoequals
@autocompareto** auto added• All fields automatically have @property,
@fortostring, @forcompareto**, @forequals
**: if Comparable implemented
![Page 148: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/148.jpg)
Struct Classes…
• Example@struct class Data implements Serializable, Comparable<Data> { int[] array; Date date; String name;}
![Page 149: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/149.jpg)
Terse Methods
• Shorten single line non-void, concrete methods
• Ex:– public int calc(int x, int y) { return x + y;}
• Becomes:– public int calc(int x, int y) = x + y;
Note: very effective on getters – public int getCount() = count;
![Page 150: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/150.jpg)
Terse Methods…
• Shorten multi-line non-void, concrete methods– Implied return value “result” of return type– Single exit point (return statement not allowed)
• Ex:– public int calc(int x, int y) = { int z = calcZ(); result = x + y + z;}
![Page 151: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/151.jpg)
Static (utility) Classes
• Allow static modifier on top-level classes– Makes all members implicitly static– Changes default viability from “default” to public– Makes any constructor, toString, equals/hashCode
declaration an error– Auto create protected default constructor– Can only extend by another static class
![Page 152: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/152.jpg)
Questions?
![Page 153: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/153.jpg)
DETAILED DEFINITIONS
![Page 154: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/154.jpg)
Operator Overloading
![Page 155: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/155.jpg)
rationale
• Difference in operator support between primitive types and reference types is highly inconsistent and results in excessive source.– Already recognized in special cases (ex. String +)– Overloading adds to code brevity, readability– Reasons for/against tend to be near religious
• Widely supported in other popular languages• Most important for numeric, collection and
stream types.
![Page 156: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/156.jpg)
Operator Overloading
• Allow custom definition of “operator” methods in any class/interface– Support many existing Java operators– Add new Java operators– Add casting capabilities (similar to numeric
primitives)
C+L++++
$$$$
Cost depends on how much JRE supports this feature
![Page 157: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/157.jpg)
Operator Overloading…
• “Operator” methods are just like other instance methods but have unusual names– Can override, overload, inherit; Select visibility– In most cases a method already exists to implement
all/part of operator (ex. BigInteger’s add() for ‘+’)– Create name mapping:
ex. + => $add (or $plus or _plus_ or ???)– Compiler invokes method upon seeing operator
• Missing/inaccessible $<op> gets compiler error– Unless built-in (ex. String +)
![Page 158: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/158.jpg)
Operator Variants
• Given Class X, Y; instance x, y (Y may be X)• Standard Operator Mappings:
– <op> x (ex. - x)• Method: x.$<op>()
– <op> x, x <op> (ex. ++ x, x ++)• Method: x.$x<op>(), x.$<op>x
– x <op> y (ex. x + y) (X & Y overload, use associativity)• Method: x.$<op>(Y y)
– y <op> x (ex. y + x) (Y does not overload <op>)• Method: x.$i<op>(Y y)
– x <op>= y (ex. x += y)• Method: x.$a<op>(Y y)
• At least one of X, Y must be reference type
![Page 159: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/159.jpg)
OperatorsName (possible method name)
Suggested Method Name
Precedence **
Note
+ Plus $pos | $add
1 | 3 Unary | Binary
- Dash $neg | $sub
1 | 3 Unary | Binary
* Star | Asterisk $mult 2
/ Slash $div 2
\ Backslash $bslash 2 New
% Percent $mod 2
& Amp $and 7
| Vbar $or 9
^ Hat | Caret $xor 8
~ Tilde $not 1
**: 0 highest; subject to change
![Page 160: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/160.jpg)
Operators…Name (possible method name)
Suggested Method Name
Precedence Note
&& Logical And 11 cannot override
|| Logical Or 12 cannot override
! Logical Not $lnot 1
![Page 161: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/161.jpg)
Operators…Name (possible method name)
Suggested Method Name
Precedence Note
< Less Than $lt 5 Also Generic Start
> Greater Than $gt 5 Also Generic End
<= LT or Equal $le 5
>= GT or Equal $ge 5
== Equals $eq 6 Cond override
!= Not Equals $ne 6 Cond override
![Page 162: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/162.jpg)
Operators…Name (possible method name)
Suggested Method Name
Precedence Note
<< Left Shift $lshift 4
>> Signed Right Shift
$srshift 4
>>> Unsigned Right Shift
$urshift 4
<<< Unsigned Left Shift
$urshift 4 New
![Page 163: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/163.jpg)
Operators…Name (possible method name)
Suggested Method Name
Precedence Note
++ Pre-increment
$xinc 1
++ Post-increment
$incx 1
++ Pre-decrement
$xdec 1
++ Post-decrement
$decx 1
![Page 164: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/164.jpg)
Operators…Name (possible method name)
Suggested Method Name
Precedence Note
<op>= Augmented Assignment
$a<op> 14
[]= Indexed Assignment
$andx 0
[] Indexed Access
$ndx 0
= Assignment 14 cannot override
(…) Call $call 0 … not type
(…) Cast $cast 1 … is type
![Page 165: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/165.jpg)
Operators…Name (possible method name)
Suggested Method Name
Precedence Note
** Power $pow 2 New
:: Bind $cat | $bind 13 New; maybe :::
==> Send $send 13 New
<== Receive $rec 13 New
… Inclusive Range
$rng 10 New
>.. Left Noninclusive Range
$xrng 10 New
..< Right Noninclusive Range
$rngx 10 New
![Page 166: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/166.jpg)
Operators…Name Precedence Note
? : Ternary 13 cannot override
?: Elvis | Default
13 New; cannot override
?. Safe-Reference
0 New; cannot override
. Member Access
0 cannot override
new 1 cannot override
instanceof 5 cannot override
( … ) Sub-expression
0 cannot override; … not type
![Page 167: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/167.jpg)
Operators…Name (possible method name)
Suggested Method Name
Precedence Note
:x Generalx is: + - / * % & | ~ \ ! < >
$colon<op> Varies based on x
New
x: Generalx is: + - / * % & | ~ \ ! < >
$<op>colon Varies based on x
New
![Page 168: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/168.jpg)
New Operators
• Given:Claxx X/Y, instance x/y• Call operator ($call) – ?? = x(…) x.$call(…)
• Cast operator ($cast)**– ?? = (<type>)x x.$cast(<type>^^.class)– Or: <type>.class.newInstance(x)
See new operators from other sections (ex. power(“**”) operator)** iff not trivial conversion like up/down cast or numeric promotion or boxing^^ reference and primitive (ex. Integer.TYPE)
![Page 169: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/169.jpg)
New Operators..
• Index operator ($ndx) – ?? = x[…] x.$ndx(…)
• Index assignment operator ($andx) – x[…] = ?? x.$andx(??, …)
![Page 170: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/170.jpg)
New Operators…
• Equals operator ($eq) – x == y x.$eq(y) iff enabled; else sameAs(x, y)
• Also $ne, $lt, $ge, $gt, $le – Pair (ex. $ne for $eq) auto-generated if missing
and other present.– Ex. boolean $ne(? x) { return !this.$eq(x); }
• $eq() and equals() need to be consistent– Say: boolean $eq(? x) { return this.equals(x); }
![Page 171: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/171.jpg)
New Operators…
• New Binary operators:– :x where x is: + - / * % & | ~ \ ! < > (maybe @)• Left associative
– x: where x is: + - / * % & | ~ \ ! < > (maybe @)• Right associative
• Intended to provide a reasonable set of new operators to apply
![Page 172: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/172.jpg)
Excluded Operators
• The following operators cannot be customized:– Object Creation (new)– Value Assignment (=) (but ?= and []= OK)– Instance of (instanceof)– Member reference (.)– Ternary (x ? y : z)– Short Circuit ( x && y, x || y)– Field literal (.@) – Safe Dereference (?.)– Elvis (?:)
Last 3 are new operators (or separators)
![Page 173: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/173.jpg)
Collection/Stream Examples…
• Examples:– List<Integer> li1 = ..., li2 = ...: – i1.add(1); li1.add(2); li1.add(3);– li1.addAll(li2);
• Vs:– li1 << 1 << 2 << 3;– li1 << li2;
![Page 174: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/174.jpg)
Collection/Stream Examples…
• Examples:– StringBuilder sb = ...;
sb.append("Hello").append(" ").append("World!"). append(‘\n’);
– Vs.– sb << "Hello" << " " << "World!" << '\n';– Also:– PrintWriter pw = ...;
pw << "Hello" << " " << "World!" << '\n';
![Page 175: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/175.jpg)
== and !=
• By default: == same, != not same
• With overloaded often want them to mean:== equals(), != !equals()
• Backward compatibility prevents default change– Add client class/method @autoequals and/or client
interface AutoEquals and/or implementation @autoequals
– Add static boolean Object.sameAs(Object x, Object y)
![Page 176: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/176.jpg)
== and !=
• Example: Compare• boolean test(String s1, Sting s2) { return s1.equals(s2);}
• With equivalent• @autoequals boolean test( String s1, Sting s2) { return s1 == s2;}
![Page 177: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/177.jpg)
Reference Initialization
• Allows easier initialization (less explicit use of constructors, etc.) of reference types
• For any Class X, Y, to initialize an X from an expression of type Y– Use static method X X.valueOf(Y) or new X(Y)– Must be unique choice or explicitly coded
• Allow trivial (ex. int -> long or boxing) adjustment of Y first if needed
• Ex. BigInteger x = 10, y = “10”;
![Page 178: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/178.jpg)
New Number Hierarchy• Number • Integral (abstract)• Byte• Char• Short• {Atomic}Integer• {Atomic}Long• BigInteger• :• Real/Fractional (abstract)• Float• Double• BigDecimal• Rational• :• Complex
Enables better placement of overloaded operator methods
![Page 179: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/179.jpg)
Example Implementation
• Examples:– In BigInteger– public BigInteger $add(BigInteger other) {
return this.add(other);}
– public BigInteger $add(String other) { return this + new BigInteger(other);}
– public BigInteger $iadd(Integral other) { return new BigInteger(other.toString()) + this;}
Only a partial set, many more for full implementation
![Page 180: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/180.jpg)
Example Implementation…
• Example: In List - list intersection (sub-optimal)• default public List<E> $and( List<? extends E> xl) { List<E> nl = Helper.makeNewList(this); nl.addAll(this); Iterator<E> it = nl.iterator(); while (it.hasNext()) { E e = it.next(); if (!xl.contains(e)) { it.remove(); } } return nl;}
Only a partial set, many more for full implementation
![Page 181: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/181.jpg)
Create a new Numeric Type• @valuetype public class Fraction {
@property long num, den;
public Fraction(long num, long den=1) { if(den == 0) throw new DivideByZeroException; this.num = num; this.den = den; normalize(); } : }
Only a partial implementation
![Page 182: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/182.jpg)
Create a new Numeric Type…• public Number $add(Fraction x) =
normalize(new Fraction(num * x.den + x.num * den, den * x.den)); public Number $add(Long x) = normalize(new Fraction(num + x * den, den)); public Number $iadd(Long x) = normalize(new Fraction(x * den + num, den)); public Number $aadd(Long x) = ** $add(x);
:
**: auto-generated id omitted on @valuetype
![Page 183: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/183.jpg)
Create a new Numeric Type…• public double $cast(Double.TYPE) =
(double)f.num / (double)f.den;public Double $cast(Double.class) = (Double)$cast(Double.TYPE);public double doubleValue() = $cast(Double.TYPE);: public String toString() = String.format(“%d:/%d”, num, den);:
![Page 184: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/184.jpg)
Create a new Numeric Type…
• Helpersprotected static Number normalize(Fraction f) { long t = gcd(f.num, f.den); f.num /= t; f.den /= t;
return f.den == 1 ? F.num : this; } protected void normalize() { normalize(this); }
protected int gcd(int x, int y) = … :
![Page 185: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/185.jpg)
Create a new Numeric Type…
• Add to Number classes
public Fraction $colonSlash(long x) = new Fraction(this.longValue(), x);public Fraction $icolonSlash(long x) = new Fraction(x, this.longValue());public Fraction $colonSlash(Number x) = $colonSlash(this, x.longValue());:
![Page 186: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/186.jpg)
Value Types
• Java primitives are value (immutable and identity-less) types where ++x; x++; --x; x--; x += 10 and similar create new values
• On reference types these operator instead update the receiver (via a method)
• Many Java reference types behave as values types (ex, String, Number) and should be treated as such: i.e., x++, x += y create new
C+L+
$$
![Page 187: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/187.jpg)
Value Types…
• Add the new @valuetype class annotation.– copy constructors generated if missing; default
constructor, setters not allowed– Compiler can auto-gen any missing ?=, --/++
methods• Apply to JRE types as appropriate (ex.
Numbers)
![Page 188: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/188.jpg)
Imports and Aliases
![Page 189: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/189.jpg)
rationale
• It should be easier to import names into a compile unit– Finer selection– Finer location (vs. whole unit)– Produce more conventional names
• It should be easier to migrate to new field / method names over time
![Page 190: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/190.jpg)
Import Aliases
• Allow imported type, field and method names to have aliases– To update to new conventions; library adoption;
personal preference• Import {static} <baseName> as <alias>, …– Only alias defined
• Import {static} <baseName> add <alias>, …– BaseName and alias defined
C+++
“add” can be ‘+’; “as” can be ‘=‘
$$
![Page 191: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/191.jpg)
Terser Imports
• Reduce redundant text when importing multiple types from a single package
• import <baseType> {:<simpleType}…• Extend wildcards: can occur 0+ times anywhere in
name– * == 0+ characters; ? == exactly 1 character
C++
$$
![Page 192: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/192.jpg)
Package Imports
• Create partial package imports– Help eliminate base name crashes from multiple
packages– Brevity
• import <package> as <alias>
C+
$
![Page 193: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/193.jpg)
Multiple Imports/Import Blocks
• Allows import to be scoped– Import can occur in any class/interface/enum
• At start of body• Symbols defined only in that type and nested children
– Import can occur in any method and/or block• At start of method/block• Symbols defined only in that method/block and nested children
– Import can have optional block• Can be anywhere in method/block• Symbols defined only in child block• Can nest indefinitely
C++
$$
![Page 194: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/194.jpg)
Type Aliases
• Allow complex types to be shortened– Some overlap with import
• Alias is same as base type• typealias <baseType> as <newType>, …– <newType> now acts like reserved word; ie. no
variable can have that name in same scope• Use anywhere a declaration is allowed
C+BC
Can be class & method member (preferred) or just compiler (after imports)
++
$$
![Page 195: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/195.jpg)
Method Aliases
• Allow methods to have alias names• methodalias <methodSig> as <nameName>, …• methodSig is like static reference without
values:– Ex. String.substring(int, int)– Empty parameters: (void)– All overloads: (…)
• Use anywhere a method declaration is allowed
C+BC++
Can be class & method member (preferred) or just compiler (after imports)
$$
![Page 196: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/196.jpg)
Field “Alias” by Annotation
• Leverage JavaBeans• Auto-generation of access methods• @alias(“x, y, z”) private int xxx– Perhaps @alias(“x, y, z, xxx”) private int _xxx
C+
$
![Page 197: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/197.jpg)
Field “Alias” by Annotation…
• Examples:– Generates:– private int _xxx– and public …• int getX() { return xxx;}; void setX(int $v) { _xxx = $v; }• int getY() { return xxx;}; void setY(int $v) { _xxx = $v; }• int getZ() { return xxx;}; void setZ(int $v) { _xxx = $v; }• Possibly also (for x, y and z):
<thisClass> x(int $v) { _xxx = $v; return this; }
![Page 198: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/198.jpg)
Method “Alias” by Annotation
• Auto-generation of methods• Visibility same as base method• @alias(“pqr, lmn”) public int xyz() { … }• @Deprecated only effects base method
C+
$
![Page 199: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/199.jpg)
Method “Alias” by Annotation…
• Examples:– Generates:• public int pqr() { return xyz(); } • public int lmn() { return xyz(); }
![Page 200: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/200.jpg)
New Collection Types
![Page 201: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/201.jpg)
rationale
• Java needs easier to use immutable types (to enable easier parallelism, for one).
• Java should provide comparable types offered by many popular languages
• For ease of use, such standard types should support literal notation.
![Page 202: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/202.jpg)
Map/List Literals
• Java has array literals, it needs to add literals for common collections
• List literal: [ <value>,… ]• Map Literal : { <key>:<value>, … }• Type is least common sub-type of key/value• Literals can be passed to constructors to set
type (or cast to type)– new ArrayList([1,2,3]) or (ArrayList)[1,2,3]
May need to use #[…] and #{…} format
C+L++++
$$
![Page 203: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/203.jpg)
rationale
• Most languages that support collections like lists, tuples, maps, etc. have some literal from for each type. Java does not.
• To match ease-of-use add the missing literal syntax
![Page 204: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/204.jpg)
Implementation
• literals create new instances upon each reference (they act as templates).
• The following creates 100 lists (thus the client can freely modify each copy).
for(int i = 0; i < 100; i++) { List<Integer> l = [ 1, 2, 3 ]; l << new Random().nextInt(100); }
• Use Arraylist and LinkedHashMap as default implementations
![Page 205: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/205.jpg)
As
• Make instanceof operator safer– Reduce boilerplate if tests
• Add public static Object methods– <T> T as(Class<T> type, Object** o ) – <T> void as(Class<T> type, Object o, <lambda>)
• Cannot throw NullPointerException– Returns null instead
C+L+++
** overloaded (independently) on primitives and Object
$
![Page 206: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/206.jpg)
As…
• Example:if(o instanceof Integer) { Integer n = (Integer)o; System.out.printf( “%d%n”, n + 1);}
• Vs.as(Integer.class, o, Integer n -> System.out.printf( “%d%n”, n + 1) );
![Page 207: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/207.jpg)
As…
• As implements standard casting unless object implements the new Castable interface which provides the cast mechanism– Method: <T> T castTo(Class<T> type)– If cannot make cast, throw ClassCastException
• Ex. class X implements Castable { … }• X x = new …; • Y y = (Y)x; x.castTo(Y.class)
![Page 208: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/208.jpg)
Collection Initialization
• Arrays support initializationnew Object[] { <value>,… }
• Collections should also:– Add new interface Loadable<T**> with methods• void load(T)• void load(T[])• void load(Collection<T>)
– Wrap values in { … } immediately after constructor call
C+L+++
** T same as collection member type
$
![Page 209: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/209.jpg)
Collection Initialization…
• Examples:• List<> l = new LinkedList<Integer>() { 1, 2, 3 } • Map<> sm = new HashMap<Integer,String>()
{ 1:”1”, 2:”2”, 3:”3” }• Key:Value pairs wrapped in Entry<K,V> class• All JRE collection classes implement Loadable– Load method differs from insert/add/append/put
in that it works only if no other method called before it (else IllegalStateException)
![Page 210: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/210.jpg)
Tuple Type
• Utility of array; flexibility of List– Implicit conversion to/from array
• Immutable fixed-size list– Can be of mixed type; supports generic types– Comparable: by length, then members
• Literal Syntax: ( <value>, … ) • Factory methods (Tuples.make) available• Allows multiple Assignment:
(int x, double y, var s) = (1, 2.0, “Three”)• Makes it easy to return multiple values
C+L+++
$$
![Page 211: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/211.jpg)
List Type
• Functional Style List• Implicit conversion to/from java.util.List
• Immutable composition– head::tail or Lists.Nil– Apparent changes create new, like with String– java.util.List like behavior + flatten()
• Literal Syntax: item1::(item2::(item3::Lists.Nil)))• Factory methods (Lists.make) also available• New “::” (maybe “:::”) ($cat) operator
C+L++
$$
![Page 212: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/212.jpg)
Range Type
• Allow a concise representation of an immutable sequence of values– Often numeric but can wrap collections
• Literal Syntax: <start> …|..<|>.. <end> { … <step>}
• Factory methods (Ranges.make) available– Can use any Rangeable ** type (+ all primatives)
• New “…”, “>..”, “..<“ ($rng, $xrng, $rngx)
**: Like Iterable (may be same)
C+L++
$$
![Page 213: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/213.jpg)
Matrix Type
• Allow a dense representation of a multi-dimensional regular (vs. ragged/sparse) arrays– Cells often primitive but can any type– Allocation is packed in memory (bit: 8 per byte)
• Access Literal Syntax: <variable>[ <index>, …]– allows [x,y,z] (instead of [x][y][z])– Support 10+ dimensions (product >0 && <=MAX_INT)
• Supply standard matrix algebra operations• Factory methods (Matricies.make) available– Create matrix and (sub)view on another matrix
C+L++
$
Simplified Subset of JSR 83
![Page 214: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/214.jpg)
Matrix Concept
• 3-dimensional [N, M, L] Matrix– N * M * L cells
• View on Matrix• View on View• Can also view as
vector (1 dimensionN * M * L long)
• Can update through view
Ignore labelsFrom http://www.altera.com/technology/system-design/articles/2013/scanned-radar-signal-processing.html
![Page 215: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/215.jpg)
Matrix Access…
• Whole Matrix and View (AKA sub-range)• Picture shows
possible additional options(stride, selection,partition, etc.)
• Do provide transformslike flip and transpose
http://incanter.org/docs/parallelcolt/api/cern/colt/matrix/doc-files/slice.gif
![Page 216: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/216.jpg)
Potential Functionality
• Get and set the cell @ index• Get rank and shape• Apply Math.* operations to all elements using lambdas• Operations to transpose, inverse, etc. • For liked shaped:
– Standard operations (ex. +, -, *, /)– CompareTo elements (produce array of ints)
• Reduction functions (sum, min/max value, etc.) using lambdas• (Consider) array construction functions (merge, pack, spread,
unpack)• Parallel operation variants where no cross-cell contention
![Page 217: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/217.jpg)
Matrix Type
• Examples:– IntMatrix m = Matrices.make(
Integer.TYPE, int[]{10, 10, 10});– Matrix vm = Matrices.makeView(m,
int[] {1}, int[]{2, 3}, int[]{5, 5});
Assume “==“ overloaded to equals(); “[]“ overloaded
![Page 218: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/218.jpg)
Matrix Type
• Examples:– int x = m[1,1,1];– m[9,9,9] = x;– Same effect:– var dims = m.getDimensions()– m[9 * dims[0] * dims[1] + 9 * dims[1] + 9] = x;
Assume “==“ overloaded to equals(); “[]“ overloaded
![Page 219: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/219.jpg)
New Numeric Types
![Page 220: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/220.jpg)
rationale
• Enhanced accuracy and safety in calculations• Extended domain of application (science,
engineering, etc.)• Make more consistent– Add java.lang.Math functions for all (not just
primitive) numeric types
![Page 221: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/221.jpg)
Rational Type
• Allow accurate representation of fractional values (such as decimal 1/3 or binary 1/10)– New Number subclasses– Support matching int/long/BigInteger as
numerator/denominator; allow normalization• Literal syntax: x :/ y (x, y some integer, y != 0)• Factory (Rationals.make)• Add similar Java/JRE support as Double has
C+L+
$$
![Page 222: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/222.jpg)
Complex Type
• Allow representation of complex values– New Number subclasses– Support matching double/BigDecimal as real/imag
• Literal syntax: x +|- yI or x @ y (x, y some non-complex number)– ‘I’ can be I, i, J, j (compile-time only, no idouble)
• Factory (Complexes.cart, Complexes.polar)• Add similar Java/JRE support as Double has
C+L+++
$$
![Page 223: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/223.jpg)
Unit & UnitValue Types
• Avoid logical errors on arithmetic across different units (ex. adding Apples & Oranges)– New Number subclasses– Add a unit to any number– Exceptions if inconsistent units in arithmetic – Can combine units and numbers with units
• Factory (Units.make, UnitValues.make)• Add similar Java/JRE support as Number has
C+L+
$$$
Much simpler approach than JSR 275; perhaps cleaner than JSR 363
![Page 224: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/224.jpg)
Unit Type
• Unit– Defines a unit that can be applied to a value– Only compatible units in an operation• Ex. + requires same units, * can combine units
– Units can be combined
![Page 225: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/225.jpg)
Unit Type…
• UnitValue– A Number that also has a Unit• Can be used anywhere a Number is allowed
– Overloaded operators supported
• Parallel to Number type hierarchy– IntegerUnitValue extends Integer, etc.– Make Integer, Double, etc. nonpackagefinal to accomplish
• Alternate**: update existing Number classes to add Unit– Numbers with null unit acts as Numbers do today
**: Number instances are larger; subtle backwards incompatibility
![Page 226: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/226.jpg)
Unit Type…
• Subtypes:– PrimativeUnit – ex: gram, second, meter, degreeKelvin– Derived/ScaledUnit – ex. kilogram, millisecond, kilometer,
degreeCelcius• Can register scale converters (similar to int float)
– CompoundUnit; ex. newton, hertz, speed• Can register formatters per unit (similar to
SimpleDateFormat)• Unit registry (localized) to access units• Add many(perhaps 100s) “standard” units– No implied naming standard; users gives name
![Page 227: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/227.jpg)
Unit Type…
• Examples:– Unit gram = Units.makeUnit("Gram", "g", "gram",
java.units.Gram);• Can have equivalents with different locales
– Number UnitValues.make(<numeric primitive>, Unit unit);
– Number UnitValues.make(<Number**> value, Unit unit);
**: not UnitValues
![Page 228: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/228.jpg)
Checked Arithmetic
• Allow for overflow/underflow detection• Add @checked(overflow=true|false|promote,
underflow=true|false|promote) method annotation– Generally used on methods containing only computations– Throws new Overflow/UnderflowException extends
RuntimeException– Applies to arithmetic and casts
• Add static <type> xxxChecked(<type> other) family of methods on primitive numbers where xxx is an operator (ex. add, multiply); generally native methods
• Promote value causes type expansion (ex. Long BigInteger) to avoid condition if Number type used
C+L++
$$
![Page 229: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/229.jpg)
Checked Arithmetic…
• Examples: Some generate exceptionsassume all in @checked(promote=true) method– Number x = 1; x << 50 - Integer BigInteger– Number x = 1024 >> 10 - Integer Double– Number x = 0x7FFFFFFF + 1 – Integer Long– Number x = (int)1FFFFFFFFL – overflow (sig bits lost)– Short s = (short)(65 * 1024) – ditto
• Casts can prevent promotion
![Page 230: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/230.jpg)
Checked Arithmetic…
• $<op> methods can accept an optional additional int parameter– Bit flags for overflow, underflow, promote– Example. • Given: Integer x, y, z;• In @checked(overflow): z = x + y;• Becomes: z = x.$add(y, Checked.overflow);
![Page 231: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/231.jpg)
Power Operator
• Allow xy to be expressed as an operator (vs. function) x ** y – New right-associative binary “**” (AKA
$power/$starstar ) operator• Add similar Java/JRE support as * (multiply)
has; on all numeric types (primitive and Big)• Example:– long x = 2**45; double y = Math.PI**-3.5**2
Assume “**” overloaded; Suggest creating BigMath class like Math class
C+L+
$
![Page 232: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/232.jpg)
Miscellaneous Enhancements
![Page 233: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/233.jpg)
rationale
• Java needs increased ease-of-use and self-consistency
• Java should provide comparable utility features offered by many popular languages
![Page 234: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/234.jpg)
“Class” literal Extensions
• Existing Class Literal: <className>.class• New Package Literal:
<packageName>.package• New Field Literal:
{<className>.}@<fieldName>• New Method Literal:
{<className>.}<methodName>(<type> {,<type>}…|void)
• All resolved (tested to exist) by compiler{<className>}: optional when inside that class; class name can be qualified
C
+
+++
$
![Page 235: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/235.jpg)
Method Bindings
• Bind a method and its receiver– First class combo (not a closure) – Overloads operator “::” (maybe “:::”) to create
• Allows “currying” via get/setParameter– Also via overloaded operator “…” – aBinding…1…2 sets the first 2 parameters
• Allows rebinding via get/setTarget• Overloads $call
C+L+++
$$
![Page 236: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/236.jpg)
Method Bindings…
• Example: (cont)• Effectively invokes:– String s2 = s.substring(0, 10);
• But actually invokes:– String s2 = substring.$call(0, 10);
• Which then calls – method s.substring(0, 10)
• via reflection or other means.
** an interface with at least one implementation
![Page 237: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/237.jpg)
Method Bindings…
• Binding supports a Boolean property: async– If true $call() may run on a separate thread• Implementation should use Executors• So may support additional configuration properties
– $call will return a Future<T> (T is original return type) to allow monitoring of the progress
– Intended to be used on only heavy-weight (does I/O, etc.) methods
![Page 238: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/238.jpg)
Method Bindings…
• Example:– MyIOService s = …;var f = (Future<Integer>) MyIOService.copyTree(File, File)::s.setAsync(true).$call (new File(“.”), new File(“elsewhere”));
: do other stuff
int rc = f.get();Optional text
![Page 239: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/239.jpg)
Add “Chaining” Setter
• For field “<type> xxx” JavaBeans defines access methods as:– <type> get/isXxx() { return xxx; }– void setXxx(<type> v) { xxx = v; }
• Add new setter:– <thisType> xxx(<type> v) { xxx = v; return this; }
• This allows “fluent” assignments like:– Xxx xxx = new Xxx().aaa(1).bbb(3).ccc(3);
• Retrofit into all JRE classes
L+++
$$$$
![Page 240: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/240.jpg)
rationale
• Long sequences of setter can get tedious• Example:• Xxx xxx = new Xxx();
xxx.setAaa(1);xxx.setBbb(3);xxx.setCcc(3);
• These need to be made less repetitive• This is a common pattern JRE should fully embrace
![Page 241: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/241.jpg)
Versioned Types
• Applies to Class, Interface, Enum• Each type can have version suffix:
[<major>{,<minor>{,<fix>{,<comment>}}}]• Matching on (internal) class name (#s only)– for class Xxx[1.2.3.zzz] name is Xxx$$v1v2v3vzzz
• Annotation better but requires full class path scans
– first matching on class path wins• System class loader change
– Compiler can generate multiple versions of source; highest version also generated wo suffix
C+L+VM+
$$
![Page 242: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/242.jpg)
rationale
• Often need to evolve classes incompatibly– Change method name/param/return type– Resort to new class name (ex. Xxxx2) or package name
(xxx.yyy.v2)– This is difficult to manage
• Alternate needed that allows most classes to be referenced by name alone– Typically unadorned; occasionally with specific
version/version range– Ex. Xxx (any version) vs. Xxx[2.0,] (any 2.0+)
![Page 243: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/243.jpg)
New Final Variant
• Final on methods prevents overriding.– Often to restrictive– Often it is safe to allow classes in the same
package to override (i.e., same careful authors)• Add new “nonpackagefinal”** keyword– Method can be overridden only by classes in same
package• Expected to be useful for java and javax
packages (ex. Number subclasses)
**: looking for better name
C+L+VM+
$
![Page 244: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/244.jpg)
Pseudo Methods
• Add dynamic methods to a class• New interface: SupportsPseudoMethods**– Method: Object onMethodCall(String
methodName, Object... args) – Implements “missing” (maybe all) methods
• Compiler redirects to above whenever a (statically, not via reflection) method is invoked that does not exist
C+L++++
$
**: looking for better name
![Page 245: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/245.jpg)
rationale
• Many languages allow classes to dynamically add method behavior. – This allows for very flexible capabilities, such as
meta-programming– Wo/complex means (such as AOP)
• Java needs a similar capability
![Page 246: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/246.jpg)
Pseudo Methods…
• Assume class Expando implements SupportsPseudoMethods
• Assume Expando class has methods:– normalMethod1(), normalMethod2() and
onMethodCall()• onMethodCall has cases for:– nowDate(), nowMillis() and other()
![Page 247: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/247.jpg)
Dynamic Variables
• Add a new field and local variable annotation @dynamic (allowed only on Object or Object[] types) – tells the compiler to ignore type safety on any
method call– Causes dynamic (via reflection, invokedynamic, etc.)
calls– Suggest add method to Object to facilitate making
these dynamic calls: $dynamicCall and $canDynamicCall
C+L+++
$
![Page 248: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/248.jpg)
rationale
• May languages support similar behavior, often call duck typing
• At the loss of some compile time proven correctness, such variables are very flexible
• Java needs similar flexibility
![Page 249: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/249.jpg)
Var Type
• Use initial value to imply variable type– Explicit type only needed if type different from
initial value’s type (say a superclass)– Saves significant typing; allows easier type change• @property var count = 1; 1L;
• Define new type “var” that accepts the value’s type– Declarations: var x = <expr>;– For: for(var x: <iterable>) { … }
C+L++
$
![Page 250: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/250.jpg)
Var Type…
• Example:– Integer ten = new Integer(10); – int thirty = 30;– int twenty = 20;– long ninety = 90L; – String name = "Barry";– double y = 30.5;– LinkedList<String> stringList1 = new LinkedList<String>();– Number x = new Integer(20); – List<String> stringList2 = new LinkedList<String>();
![Page 251: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/251.jpg)
String Enhancements
• Simple (JavaIdCharacter content only): `this_is_a_string (makes great hash key)
• Long Strings: “”” any text here, including “ and ‘ and \n and line ends until the next “””
• Raw Strings (ignore ‘\’ as escape):– “this \ is not an escape”R (or r)– Also “”” … “””r
C+L
+
+++
++
$
![Page 252: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/252.jpg)
String Enhancements…
• Smart Strings: ~“””${name} is ${age > 50 ? ”old” : “young” }””” **– Simple id reference can be shortened: $name
• Causes any ${<expr>} to be replaced by the value of the <expr> evaluated in current context – May cause internal Map to be sent to interpolate()
with all (perhaps just referenced in expr) variables in current context.
**: overloaded operator does “interpolate()” (ah la Perl/Groovy) behavior
+
![Page 253: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/253.jpg)
String Enhancements…
• Unified StringBuilder/Buffer and String– Create new Interface Stringy that covers all String
instance methods– Make StringBuilder/Buffer implement Stringy• So they can be used most places Strings are• Replace most JRE methods String parameters with
Stringy type
– The compiler will treat Stringy items as String (ex. x + y)
+++
![Page 254: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/254.jpg)
Size Enhancements
• Unify size determination– Add new Interface Sizable with method: int size()– Add method and/or interface to all JRE classes
with size(), length() or getLength() methods• Ex. Add CharSequence method: default int size() =
length()• Consider adding int size() to array classes
+++
![Page 255: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/255.jpg)
Default Positional Parameters
• Allow optional default values for parameters– Added convenience; many languages support them
• Parameter Syntax: <modifier>… <type> <name> { = <value>}– Defaulted parameters must come after all non-defaulted
parameters; omission applied right-to-left– Values must be constant expressions or null
• Works by generating methods with/without params and calling all param version– Unless provided by programmer
C+L++
$
![Page 256: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/256.jpg)
Reference Parameters
• Add new @ref ** parameter annotation– Allows pass-by-reference parameters– Allows multiple return values
• Actual parameter values must be a variable (vs. expression) so it can be assigned to• Variables passed must also be declared @ref
• Implementation may implicitly auto-box variable and pass boxed value by value
**: perhaps @inout
C+L+
$
![Page 257: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/257.jpg)
“Keyword” Parameters
• If last constructor or method parameter is Map<String,?> (like … works) you can use a map literal as last parameter – Normal form: {k1:v1, k2:v2} – Concise form: k1:v1, k2:v2– Actually can intermix with positional parameters
C+L++
$$
![Page 258: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/258.jpg)
“Keyword” Parameters…
• If no map as last parameter on a constructor use this sequence for keyed values:– Xxx xxx = new Xxx(1, 5); – xxx.setX(1);– xxx.setY(2);– xxx.setZ(3);
• “Defaults” for keys:– Add new Map method: Map putIfNew(key, value)– Use in called method to set “defaults”
![Page 259: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/259.jpg)
Pseudo Instance Methods
• Redirect undefined (unless SupportsPseudo-Methods processing) methods to best known (imported) matching static methods– Match if name same, first param is receiver type (or
supertype), other params match in turn– Match must be unique or compiler error
• Only on instance methods• At compile-time only• Even on final classes• Not polymorphic, but overrideable
C+L+++
$
![Page 260: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/260.jpg)
Pseudo Instance Methods…
• Examples:• Given:
– public class X { … }– public class SomeUtilClass {
public static void doThis(X x, int a, in b, int c) {…} public static void doThat(X x, int a, in b, int c) {…}}
![Page 261: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/261.jpg)
Pseudo Instance Methods…
• Examples:– Class X has no doThis/doThat methods
• These calls:• X x = new …• x.doThis(1, 2, 3)• x.doThat(3, 2, 1)
• Becomes:• SomeUtilClass.doThis(x, 1, 2, 3)• SomeUtilClass.doThat(x, 3, 2, 1)
![Page 262: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/262.jpg)
Constant References
• Final on primitives implies constant• Final on references allows referent to still change• Add new reference variable annotation @const
which disallows update of referent– No assignment to referent fields– No use of non-const methods via reference
• Allow @const on instance methods, which indicates method does not mutate** receiver
• Apply to JRE methods as appropriate– @property adds @const on getters
C+L++
**: can allow internal only changes (ex. normalize a rational value)
$$
![Page 263: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/263.jpg)
Stable (pure) Methods
• Some methods, given the same inputs, will always produce the same outputs. If the compiler (source/JIT) knows this, optimizations are possible.
• Add a method @stable annotation which allows the optimization of repeated (in source or loop) method calls to be cached– Only if the compiler can detect that the parameters are
the same on each call• Annotate all @stable JRE methods– Ex. Math.min()/max()
C+L+
$$
![Page 264: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/264.jpg)
Stable (pure) Methods…
• Stable parameters:– Compiler flows indicates not changed– Type is:
• Immutable (including primitives and null) or Value Type• Accessed via @const Reference• Result of another stable method
• Add new @immutable annotation – Marks type as immutable (often also with @valuetype)
• Type should** have no mutators
– Mark all immutable JRE types (ex. Numbers)– Add annotation to Collections immutable method returns
**: can allow internal only changes (ex. normalize a rational value)
![Page 265: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/265.jpg)
Specialized toString
• Split toString() into– humanToString() – intended for humans• May be minimalist (like String.toString())
– debugToString() – intended for programmers– Should always look like Object’s toString
– Each type selects which form toString() uses
L++
$$$
Cost depends on how much JRE adopts this approach
![Page 266: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/266.jpg)
Specialized toString…
• Make each xxxxToString() method composable– xxxxPrefix(), xxxxBody(), xxxxSuffix(),
xxxxBodyStart(), xxxxBodyEnd()– All take StringBuilder arg– Perhaps all start with ‘$’
![Page 267: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/267.jpg)
Specialized toString…
• Ex:public String debugToString() { StringBuilder sb = new ..; $debugPrefix(sb); $debugBodyStart(sb); $debugBody(sb); $debugBodyEnd(sb); $debugSuffix(sb) return sb.toString();}
• Allows subclasses opportunity to override minimally (ex. override $debugBody() only)– @autotostring supports this structure
![Page 268: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/268.jpg)
Get Compile Time
• Add Class method: long getCompileTime()– Milliseconds since epoch
• Allows build time to be easily accessed– Avoid class path walking, etc.
L+
$
![Page 269: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/269.jpg)
For with Index
• Enhance the “Enhanced For” Statement to provide index and count– Provides index of current iteration– Provides max number of iterations
• Syntax ex: for(int i, len; String s: aStringArray) { … }– Optional first int has current index (0+)– Optional second int has length (if known) – “int” type fixed so optional
C+
$
![Page 270: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/270.jpg)
Enhanced Switch
• Add new interface Case with methodboolean matches(Object other)
• Switch can test any type implementing Case– Use if/else If/else implementation– Implement Case on (at least) any JRE Comparable class and
enums– Consider adding Object method matches() so all types can be
used in switch (thus no Case interface needed); defaults to calling equals()
• Can eliminate special String/enum support• More readable than if/else if/else sequences
C+L+++
$
![Page 271: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/271.jpg)
Enhanced Switch
• Example:• Class z = new ….;switch(z) { case String.class: : break; case Xxxx.class: case Number.class: : break; :}
![Page 272: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/272.jpg)
Enhanced Switch…
• Allow “goto” case instead of break • Class z = new ….;switch(z) { case String.class: : break; case Xxxx.class: case Number.class: : goto String.class;}
+
![Page 273: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/273.jpg)
Enhanced Switch...• An alternate to:
– Allows finer control over flow (vs: top down only)– Some sequences cannot be done in strict top-down
• Class z = new ….;switch(z) { case Xxxx.class: case Number.class: : case String.class: : break; :}
![Page 274: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/274.jpg)
Appendable Ehnancements
• Make Appendable more like Streams– default Appendable appendln(CharSequence cs) { append(cs); append(‘\n’); return this;}
– default Appendable appendf(String fmt, Object…va) { append(String.format(fmt, va); return this;}
L++
$
![Page 275: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/275.jpg)
Basic JSON Support
• Add basic++ JSON support based on collections– New JsonObject extends TreeMap<String, ?>– New JsonArray extends ArrayList<?>– Values restricted to: null, String, Number**,
Boolean– Both have static parseJson(String) to parse– Has String toJsonString(boolean formatted)– Both implement new JsonValue marker interface
++ way less than Java API for JSON Binding; **: perhaps just Double
L++
$$
![Page 276: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/276.jpg)
Basic XML Support
• Add basic XML support based on collections– New XmlNode interface/ XmlTextNode impl• Method: String getText()• Method: String toXmlString(boolean formatted)
– New XmlElement extends LinkedHashMap<String, String> implements XmlNode• Map holds attributes• Contains: @property List<XmlNode> elements• Has static parseXml(String) to parse• Has static to/FromDom for DOM integration
No support to see other XML (instructions, comments, etc.)
L+
$$
![Page 277: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/277.jpg)
Simplified Serialization
• Serializing into a stream is often awkward– Large amount of overhead
• Serialize into List or Map (vs. Stream)– Much easier to manipulate– Can stream serialize resulting map/list if needed– Target/members must still be serializable – Reference loops allowed– May lose primitive vs. wrapper type distinction– May lose array vs. collection distinction
• Add utility methods to serialize/deserialize
L+
$$
![Page 278: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/278.jpg)
Implements Visibility
• Allow private, protected or public implements– Public – default; All client classes see methods;
same as current– Protected – only this class or sub-classes know
methods defined– Private – only this class know methods defined
• Ex. class X private implements IX { … }• instanceof only true when visibility allows
C+L+
$
![Page 279: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/279.jpg)
Pseudo Implements
• Allow a class that identically implements all the methods of an interface to be treated as if it implements the interface even if it formally does not.– Ex. usage: interface created after class written wo
access to class source to add implements• May need to auto-generate a Proxy object to
implement
C+L+++
$$
![Page 280: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/280.jpg)
Pseudo Implements…
• New @implicitimplements annotation– On class: validates class acts like it implements
<interface> value (optional, like @Overrides) ; error if class is missing any required method
– On field/method local: One can pass/assign a type that conforms even if <interface> not implemented
– New Class method: boolean conformsTo(<interface>)• True if assignable or all methods are implemented
![Page 281: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/281.jpg)
Default Visibility
• Allow use of “default”** keyword as a visibility• Allows explicit setting (vs. just implied by
absence)• Add compiler switch to force use to get default
visibility (i.e., can’t declare type/member without explicit visibility modifier)
**: possibly use “package” keyword
C+L+
$
![Page 282: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/282.jpg)
Boilerplate Reduction
![Page 283: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/283.jpg)
Terse Methods
• Shorten single line non-void, concrete methods
• Ex:– public int calc(int x, int y) { return x + y;}
• Becomes:– public int calc(int x, int y) = x + y;
Note: very effective on getters – public int getCount() = count;
C+
$
![Page 284: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/284.jpg)
Terse Methods…
• Shorten multi-line non-void, concrete methods– Implied return value “result” of return type– Single exit point (return statement not allowed)
• Ex:– public int calc(int x, int y) = { int z = calcZ(); result = x + y + z;}
![Page 285: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/285.jpg)
Terse Methods…
• Another Example:• boolean isEqual(Object l, Object r) = { if(l == null) result = r == null; else result = r == null ? false: l.equals(r);}
L+++
![Page 286: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/286.jpg)
Terse Methods…
• Even Briefer:• boolean isEqual(Object l, Object r) = l == null ? r == null : (r == null ? false: l.equals(r));
L+++
![Page 287: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/287.jpg)
Static (utility) Classes
• Allow static modifier on top-level classes– Makes all members implicitly static– Changes default viability from “default” to public– Makes any constructor, toString, equals/hashCode
declaration an error– Auto create private default constructor
+C
$
![Page 288: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/288.jpg)
New Safe Dereference Operator
• Shorten common Java idiom• Safe Dereference: x .? y– Short for: x != null ? x.y : null
• Can cascade: (ex. x.?y.?z)• Ex.– String city= user?.address.?city– Vs: String city = (user != null ?(user.address != null ?
(user.address.city) : null) : null)• Conside @autosafe class/method annotation– Converts use of “.” to “.?”
C+++
$
![Page 289: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/289.jpg)
New Default Operator
• Shorten common Java idiom• Default (Elvis): x ?: y– Short for: isTrue(x) ? x : y– Uses Java truth (!null, !0, !false); returns x if It is
“true”, else y
C++
$
!!: Operators && and || also do this
![Page 290: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/290.jpg)
New Default Operator…
• Truth– If x is a non-null reference type and type
implements (new) IsTruth interface, test it !!• Retrofit isTruth to JRE as appropriate
– IsTruth has: boolean isTrue() • Ex. String.isTrue() { return length() > 0; }• In general empty false• Consider Number.isTrue() { return this.value != 0; }
!!: Operators && and || also do this
![Page 291: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/291.jpg)
Property Definition
• Add @property field** annotation• Causes automatic access method generation– Unless programmer defined
• Supports simple, 1-dim array and generic types
C+L+++
$$
**: allowed in both class (bodies provide) and interface
![Page 292: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/292.jpg)
Property Definition
• Values: – observable|vetoable=true|false• Auto-generate add/removeListener• Auto-generate fireListeners
– visibility: control access method visibility• (public visibilities) rw(default), ro, wo; private
– name: alternate name (vs. field) to name the property
**: allowed in both class (bodies provide) and interface
![Page 293: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/293.jpg)
Property Definition…
• Example (in class X):– @property(vetoable=true) String ssn;
• Generates code similar to this:– private String _ssn;– @const public String getSsn() { return _ssn; }
![Page 294: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/294.jpg)
Property Definition…
• Example (continued):– private List<PropertyChangelistener> _listeners = …; **
– public void addPropertyChangelistener( PropertyChangelistener l) { … } **
– public void removePropertyChangelistener( PropertyChangelistener l) { … } **
**: only on topmost class needing this
![Page 295: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/295.jpg)
Property Definition…
• Example (continued):– public void setSsn(String ssn) { try { _firePropertyChangeListener( new PropertyChangeEvent( this, “ssn”, _ssn, ssn); _ssn = ssn; } catch (VetoException e) {}; }
– public X ssn(String ssn) { setSsn(ssn); return this; }
![Page 296: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/296.jpg)
Property Definition…
• Example (continued):– protected void _firePropertyChangeListeners( PropertyChangeEvent e) { // walk listeners with callback}
– Listener may/may not throw VetoException– More complex (ex. indexed) properties may have
more get/set methods
![Page 297: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/297.jpg)
Direct Property Access
• Support property access by simple name (vs. get/set method)– Supported by many languages, such as Groovy, C#– Hides difference between fields and properties
• On any field defined by @property, the field can be referred to by name only.– ex. xxx reference auto-mapped to getXxx/setXxx methods– Property name xxx would hide field name xxx so base field
name must be different (but based on) the property name • Ex. @property xxx has field _xxx
C+L++
$
![Page 298: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/298.jpg)
Direct Property Access…
• Example:– class X { @property int a, b, c; public void xxx() { a = b + c; }}
– In other classX x = new x();int z = x.a + x.b + x.c;
![Page 299: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/299.jpg)
Direct Property Access…
• Example: Acts like:– class X { int _a, _b, _c; public void xxx() { setA(getB() + getC()); }}
– In other class:X x = new x();int z = x.getA() + x.getB() + x.getC();
![Page 300: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/300.jpg)
Direct Property Access…
• Reverse the support– If no @property but both public <type> getX() and
void setX(<type> t) methods exist in a class with a inaccessible field the field can be accessed via a (pseudo) field reference• Only outside the owning class
– Ex. given: Y y = new Y();y.x += 2;
– Acts as:y.setX(y.getX() + 2);
![Page 301: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/301.jpg)
Direct Map Key Reference
• Map types support get/put by key (ex. map.get(“key”))– Or with operator overloading (ex. map[“key”])
• Further simplification (pseudo fields) can be done for String keys (ex. map.key) – “field” name must be valid JavaId or must be
String literal– Change any reference to a “field” on a Map
instance** to a get(“field”)/put(“field”, …)**: unless instance type actually declares such a field/property
C++
$
![Page 302: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/302.jpg)
Direct Map Key Reference…
– Example:• Given:
Map<String, String> map = …;• Then:
map.name = map.first + ‘ ‘ + map.last;• Equivalent:
map.put(“name”, map.get(“first”) + ‘ ‘ + map.get(“last”));• Also:
map.”has \n blank”r = “new”;• Complex expressions must use [ … ]:
map[map.first + ‘ ‘ + map.last] = “new”;
![Page 303: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/303.jpg)
Direct Map Key Reference…
– Map adds default $call operator method• Allows maps to act much like JavaScript objects
– Given: Map<String, Object> map = new HashMap<>(name: “Barry”,ucase: { String s -> return s.toUpperCase(); });
– Then:String uc = map.ucase(“hello” + map.name);
![Page 304: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/304.jpg)
Direct Map Key Reference…
– Alternate: Map<String, Object> map = new HashMap<>() { name:“Barry”, ucase:{ String s -> return s.toUpperCase(); } };
– Alternate:Map<> map = { name:“Barry”, ucase:{ String s -> return s.toUpperCase(); } };
– Then:assert “HELLO BARRY”.equals( map.ucase(“hello” + map.name));
![Page 305: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/305.jpg)
Extended Auto-Boxing
• On any use of a primitive literal, variable or expression if followed by dereference operator (“.”) and a method call then auto-box the primitive and apply the method to the wrapped value.
• Add utility methods to all wrapper types– Ex: Integer.upTo(int max, Lambda)
1.upTo(10, x -> System.out.println(x)); **– Java.lang.Math functions– Etc.
**: Also can achieve as: 1..<10.each(x -> System.out.println(x));
C+L+++
$
![Page 306: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/306.jpg)
Simplified Default Processing
• Often a failed calculation has a default value. • Example:int rc; try { rc = <some expression>;} catch (<exception> e) { rc = <default expression>;}
C+
$
![Page 307: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/307.jpg)
Simplified Default Processing…
• Make this more conciseint rc = <some expression> default <default expression>;
• Orint rc = <some expression> catch (NPE e) default <def1> : more catch clauses if needed default <def2>;
![Page 308: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/308.jpg)
Simplified Default Processing…
• Exampleint rc = Integer.parseInt(s) default 0;
• If s is “55”; rc == 55• If s = “bad value”; rc == 0
![Page 309: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/309.jpg)
Delegate Fields
• Allow implementation to be delegated• New @delegateto instance field annotation– Add any non-private method/constant in target
type to this class• Generated method forwards to target field• Dup methods are error unless provided by programmer• Only if not programmer defined
– Add any interfaces implemented by field type
C++
$
![Page 310: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/310.jpg)
Delegate Fields…
• Example:– Given: class X { public static final int A = 1; void a(); void b(); void c();}
– Given: class Y { public static final int Z = 1; void x(); void y(); void z();}
![Page 311: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/311.jpg)
Delegate Fields…
• Example:– Given: class Z { @delegateto @property X x; @delegateto @property Y y void a() { … } void b() { … } void z() { … }}
![Page 312: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/312.jpg)
Delegate Fields…• Example:
– Generates: class Z implements X, Y { public static final int A = 1; public static final int B = 1; private X _x; private Y _y; void a() { … } void b() { … } void c() { _x.c(); } void x() { _y.x(); } void y() { _y.y(); } void z() { … } }
![Page 313: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/313.jpg)
Auto-generate methods
• Many (most) classes have tedious to code and fragile implementations so automate their creation.
• Add class annotations to auto-generate– @autotostring, @autoconstructors**, @autoequals (also
hashCode), @autocompareto – @fortostring, @forequals, @forcompareto (shorter @forall)
• Each generated method uses marker field annotations to select values to include
• May actually apply to getter method (vs. field) • Each has optional parameter depth=shallow|deep|sizeOnly
– Only if not programmer defined• Update JRE classes to use where appropriate
**: all constructors in superclass
C+++
$$
![Page 314: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/314.jpg)
Auto-generation of common methods…
• Example@autocounstructors @autoequals @autostring @autocompareto class X implements Compareable { @forall @property String name; @forall @property int age;}
**: all constructors in superclass
![Page 315: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/315.jpg)
Auto-generation of common methods…
• Generates• class X { String _name; String getName() { return _name; } void setName(String t) { _name = t; } :}
**: all constructors in superclass
![Page 316: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/316.jpg)
Auto-generation of common methods…
• Generates• class X { : int _age; int getAge() { return _age; } void setAge(int t) { _age = t; }}
**: all constructors in superclass
![Page 317: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/317.jpg)
Auto-generation of common methods…
• Generates• class X { : public String toString()** { return … + “name=“ + _name + “, age=“ + age + …; }}
**: some license on implementation for brevity
![Page 318: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/318.jpg)
Auto-generation of common methods…
• Generates• class X { : public boolean equals(X x)** { return … && this._name.equals(x._name) && this._age == x._age; }}
**: some license on implementation for brevity
![Page 319: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/319.jpg)
Auto-generation of common methods…
• Generates• class X { : public int hashCode(X x)** { return … + _name.hashCode() + _age; }}
**: some license on implementation for brevity
![Page 320: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/320.jpg)
Auto-generation of common methods…
• Generates• class X { : public int compareTo(X x)** { int p1=_name.compareTo(x._name) int p2=_age - x._age; return p1 != 0 ? p1 : p2; }}
**: some license on implementation for brevity
![Page 321: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/321.jpg)
Auto-generation of Constructor
• Many constructors just map parameters to fields; this can be automated (via @auto annotation)
Parameters names must match field names• Ex:
public Xxx(int a, int b, String s, Thread t) { this.a = a; this.b = b, this.s = s; this.t = t;}
• Can be achieved by:@auto public Xxx(int a, int b, String s, Thread t);
C+
$
![Page 322: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/322.jpg)
Auto-generation of Constructor…
• Allow addition of parameter:– @auto value used as parameter value
• @auto(4) public Xxx(int a, int b, String s, Thread t);
• Generates:public Xxx(int a, int b, String s, Thread t) { this(a, b, s, t, 4);}
![Page 323: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/323.jpg)
Auto-generation of Constructor…
• Which allows:• @auto(-1) public Xxx(int a);• @auto(“”) public Xxx(int a, int b);• @auto(null) public Xxx(int a, int b, String s);• @auto(4) public Xxx(int a, int b, String s,
Thread t);• @auto public Xxx(int a, int b, String s,
Thread t, int size);
![Page 324: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/324.jpg)
Struct Classes
• Many class are data-only (have little/no behavior) so make them easier to create
• Add @struct class annotation– @autotostring, @autoconstructors, @autoequals
@autocompareto auto added• All fields automatically have @property,
@fortostring, @forcompareto, @forequals
*: if Comparable implemented
C++
$
![Page 325: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/325.jpg)
Struct Classes…
• @struct class can inherit only @struct class• @struct can implement any interface• @struct can have constructors
*: if Comparable implemented
![Page 326: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/326.jpg)
Struct Classes…
• Example@struct class Data implements Serilizable { int[] array; Date date; String name;}
![Page 327: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/327.jpg)
Partial Classes
• Often single class source files get too big or need to be split across developers (human and/or machine).
• Allow a single top-level class to be defined in multiple source files
• Add the @partial class annotation (on each part)• Extend the class name to be <primaryName>{-
partial#}.java <primaryName>.class– partial# files processed in ascending order; may have gaps– Single logical class body created from primary and each
partial part
C+
$
![Page 328: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/328.jpg)
Partial Classes
• Imports combined across files• Package statement must be same in all files– All -partial# sources must be in same directory as
primary• Visibility needed only in main file
![Page 329: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/329.jpg)
Partial Classes…
• Example: in Xxxx.java@partial public class Xxxx { @property int x, y, z;}
• Example: in Xxxx-partial1.java@partial class Xxxx { public int sum() { return x + y + z; }}
![Page 330: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/330.jpg)
Partial Classes…
• Example: in Xxxx-partial10.java@partial class Xxxx { public int diff() { return x - y - z; }}
![Page 331: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/331.jpg)
Partial Classes…
• Example: As interpreted by javacpublic class Xxxx { @property int x, y, z; public int sum() { return x + y + z; } public int diff() { return x - y - z; }}
![Page 332: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/332.jpg)
Utility Libraries
• Raise the bar (significantly) on the support standalone JRE can provide– Standardize behavior; extend closed classes– Many sites want to constrain adding OSS
• Add utility methods/classes from popular Open Source Projects– Survey popular; ex. Apache, Google, SourceForge– List TBD (and growing per Java release)– Likely add many 100s of methods (fewer classes)– Generally small (<100 LOC) and well tested in wild
L+++
Cost/Importance varies with scope/quantity of included libraries
$$$
![Page 333: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/333.jpg)
Utility Libraries…
• Example of one such method: safe equality• Add public static Object method:boolean isEqual(Object l, Object r) { if(l == null) return r == null; else return r == null ? false: l.equals(r);}
L+++
![Page 334: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/334.jpg)
Utility Libraries…
• Example of one such method:– Allows same syntax primitive or reference types– No automatic conversion of primitive to wrapper• But cast allowed: isEquals((Integer)1, (Number)2)
• Add public static Object method:boolean isEqual( <prim>** l, <prim> r) { return l == r;}
L+++
** any primitive
![Page 335: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/335.jpg)
Conditional Methods
• Add new method annotation @conditional(name=<name>, value=<value>)
• If name == value generate method else generate nothing
• If method not generated, all calls (in same/different source) are not generated– Similar to #if() … #endif in C/C++
C+
$
![Page 336: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/336.jpg)
Duplicate Methods in Interface
• It is possible to define the same** method in multiple interfaces and thus inherit multiple methods when implementing the interfaces– Today Java folds them into one method, but this
may break semantic meaning of the methods• Allow clients to select implementation of each
method– Qualify by interface– By default one implementation covers all
C+
** This requires same signature in all interfaces; if different, always compiler error
$
![Page 337: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/337.jpg)
Duplicate Methods in Interface…
• Example:class A implements X, Y, Z { public void x() { …} // X’s x() public void y() { …} // Y’s y() public void z() { …} // Z’s z() public void X.a() { …} // X’s a() public void Y.a() { …} // Y’s a() public void Z.a() { …} // Z’s a() public void a() { …} // A’s a()}
A’s a() covers any missing others
![Page 338: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/338.jpg)
Source Partitioning
• Indicate logical sections in source– Improve readability of source for large files– Allow IDE/editor to present subsections only• Expand/contract by section
– Compiler directives• #section “<name>”• #endsection “<name>”• Can nest
C+
$
![Page 339: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/339.jpg)
Parallel Processing
![Page 340: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/340.jpg)
Parallel For
• Add new statement parallelfor (or parallelFor)– Can execute each iteration in parallel– Any uncaught exception or break interrupts all
running iterations; no new iterations start– continue ends an iteration– Loop ends when all iterations end
• Syntax like “Enhanced For” but add Map of options
• Must have finite & determinable # elements
C+L+
$$
![Page 341: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/341.jpg)
Message Processing
– Wikipedia: The Actor model in computer science is a mathematical model of concurrent computation that treats "actors" as the universal primitives of concurrent digital computation: in response to a message that it receives, an actor can make local decisions, create more actors, send more messages, and determine how to respond to the next message received.
– This JSR fully meets the above definition
L+++
$$
![Page 342: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/342.jpg)
Message Processing
• Do asynch processing by messages– Avoid synchronized blocks, AtomicXxxx, etc.– Loosely coupled Actors
• Actors receive messages and process them– Messages queue up per actor– Serialized delivery per actor– Multiple actors can be processing messages
concurrently
![Page 343: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/343.jpg)
Implementation Fundamentals
• Lightweight and easy to use• Pure-Java (no AOP, etc.)• Configurable and dynamic• Key Concepts (interfaces with default
implementations)– Actor – unit of execution; processes 1 message at a time– Message – defines an action, has from, to, subject, data,
etc.– ActorManager – manages actors; allocates threads to
actors to process messages
![Page 344: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/344.jpg)
Implementation Fundamentals…
• Managers own 0+ Actors• Managers manage
0+ Threads• Actors buffer
0+ Messages• Managers send
messages to Actors• Actors use Threads to
process messages
Manager Actor
Message
*
*
Thread* Per Message
![Page 345: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/345.jpg)
ActorManager
• Actor lifetime management• Actor runtime lifecycle management• Message sending services• DefaultActor-
Manager implementation– Adds more API,
including thread pool management
![Page 346: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/346.jpg)
Actor Lifecycle
1.New2.Activate3.Run4.Receive (repeated)5.Deactivate6.Garbage
Activated
Run
Deactivated
Idle
ReceiveSuspended
Shutdown
New
Consumes thread in receive state
Note: Actor extends Runnable
![Page 347: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/347.jpg)
Execution Model
• Multiple actors, possibly of different types, cooperate by sending messages to each other.– Sends can fail - count limit exceeded, bad subject, etc.
• Each actor has a queue of pending (received) messages. Actor can scan ahead and pick
• When a thread is available, the manager dispatches an actor’s receive method passing in the next message.– Receive should be short lived
![Page 348: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/348.jpg)
Execution Model…
![Page 349: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/349.jpg)
Message Processing Visualization• GUI shows any activity• Controls at top select
example and control execution
• Green bar shows active threads (over 1s)
• Circle shows active actors and messages between them (this instant)– Small squares show
active threads– Lines show messages– Red lines active
• Bottom circles show recent history
• Right pane show log trace
![Page 350: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/350.jpg)
Message Processing…
• ActorManagers manage threads and actors– Implement dispatching policy, etc.; deliver
messages– # concurrent messages <= # actors; … <= # threads
• Messages contain sender, target(s), category, data, timestamp, sequenceNumber, etc.
• New send operator (“==>” or $send)
![Page 351: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/351.jpg)
Message Processing…• Example:
ActorManager am = ...;Actor a1 = am.createAndStartActor(...), a2 = am.createAndStartActor(...), a3 = am.createAndStartActor(...);:Message m1 = ..., m2 = ...; m3 = ...;:
![Page 352: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/352.jpg)
Message Processing…
• Example::m1 ==> a1;int count = m2 ==> (a1, a2, a3);if(count != 3) { // message(s) not accepted, do some recovery }
![Page 353: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/353.jpg)
Message Processing…
• Broadcast (Category) Send:{`subject: `init, `data: {1, 2, 3}, `category:"*" } ==> am;
• Single Send{`subject: `exec, `data: {`ts:new Date()} } ==> a1;
![Page 354: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/354.jpg)
Message Processing…
• Given:class Accumulator extends DefaultActor { @property long result, count; @property Future<Long> done;
public Accumulator() { addCategory(`acc); }
![Page 355: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/355.jpg)
Message Processing…
• Given: @Override protected void receive(Message m) { switch(m.subject) {
: cases per subject default: super.receive(m); } }
![Page 356: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/356.jpg)
Message Processing…• Cases: : case ‘accumulate: if(count > 0) { result += (Integer)m.data; count--; if(count == 0) done.set(result); } break; case ‘init: result = = 0; count = (Integer)m.data[0]; done = (Future<Long>)m.data[1]; break;
![Page 357: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/357.jpg)
Message Processing…
• Given:class Summer extends DefaultActor { public Summer() { addCategory(`sum); }}
![Page 358: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/358.jpg)
Message Processing…
• Given:
@Override protected void receive(Message m) { switch(m.subject) {
: cases per subject default: super.receive(m); }
![Page 359: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/359.jpg)
Message Processing…
• Cases: : case ‘sum: var value = (Tuple<Integer>)m.data; var sum = value[0] + value[1]; { `subject:`accumulate, `data:sum, `category:`acc } ==> actorManager; break;
![Page 360: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/360.jpg)
Message Processing…
• Example: In main codefinal var numberSummers = 10, numberThreads = 10;var am = new DefaultActorManager(numberThreads);
var accumulator = am.createAndStartActor( Accumulator.class);
![Page 361: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/361.jpg)
Message Processing…
• Example: (cont)
1.upTo(numberSummers, -> am.createAndStartActor( Summer.class );am.start();
![Page 362: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/362.jpg)
Message Processing…
• Example: (cont)
var values = (0,1000)..<(0,2000); Future<Long> f = new …;
{ `subject:`init, `data: (values.size(), f) } ==> accumulator;
![Page 363: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/363.jpg)
Message Processing…
• Example: (cont)
values.each( v -> { for(;;) { int count = {`subject:`sum, `data: v, `category:`sum } == > am; if(count > 0) break; Thread.sleep(1); }
});
![Page 364: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/364.jpg)
Message Processing…
• Example: (cont)
: do other work
System.out.printf( “Result is %d%n”, f.get());am.clear();
![Page 365: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/365.jpg)
Services Foundation
• Allow for registration and management of Services– Service: An implementation of 1+ interfaces– Registry: a services repository
• All client location of service is indirect– No use of new, factory methods, etc. to access– Only via Registry• Allows service implementation to evolve
L+++
$$
Cost depends on how widely implemented
![Page 366: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/366.jpg)
rationale
• Currently service clients are tightly coupled to the service implementation– Client often creates (new) service or finds existing
(singleton) instance– Service lifetime bound to clients
• Third party OSS (such as Spring DI, OSGi) provide solutions; JRE should offer an option– Simple in design but extendable
![Page 367: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/367.jpg)
Services
• New Service interface– Represents a service– Methods:• Id** getId() • void start(ServiceContext)• void stop()
**: Likely Serializable
@struct class ServiceContext { Registry owner; :}
![Page 368: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/368.jpg)
Registry
• New Registry extends Service interface– Collection of Services• Any change fires listeners
– Methods:• Id register(Object o, String name,
ServiceDescriptor desc)• void update(Id id, Object o)• boolean remove(Id)
@struct class ServiceDescriptor { Class interface; String version**;}
**: in form - <major>.<minor>{.<fix>{.<build>}}
![Page 369: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/369.jpg)
Registry…
• New Registry interface– Methods:• ServiceHandle<T> [] lookup(String interface,
String version)• ServiceHandle<T> [] find(Query q)• ServiceHandle<T> get{Required}Service(Class<T> type)• ServiceHandle<T> get{Required}ServiceById(…, Id id)• ServiceHandle<T> get{Required}ServiceByName(…,
String name)
![Page 370: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/370.jpg)
Registry…
• New Registry interface– Methods:• Registry[] getChildren()• void addChild(Registry)• void removeChild(Registry)• boolean hasChildren
![Page 371: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/371.jpg)
Registry…
• New Registry interface– Each service can have values (AKA attributes) used
by queries– Methods:• void setValue(Id id, String name, Object value)• Object getValue(Id id, String name)• String[] getValueNames(Id id)• Object removeValue(Id id, String name)
![Page 372: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/372.jpg)
ServiceHandle
• New ServiceHandle interface– Each service is accessed indirectly via a
ServiceHandle<T>– Handle lifetimes should be short• Refresh on each new major access• Allows each to represent different implementation over
time
![Page 373: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/373.jpg)
ServiceHandle…
• New ServiceHandle extends Closeable interface– Methods:• ServiceDescriptor<T> getServiceDescriptor()• <T> resolveService()• void close()
![Page 374: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/374.jpg)
Adoption
• Add SystemRegistry– Registery sr = System.getSystemRegistry()• Acts as bootstrap registry
– Register all other JRE services with registry– Allows evolution:• Runtime rt = Runtime.getRuntime()
Runtime rt = sr.getRequiredService( Runtime.class)• Migrate JRE to use new approach
– @Deprecate original access methods
![Page 375: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/375.jpg)
Injection
• Simple Dependency Injection– When an instance is registered with a registry, any
dependencies are injected• Immediately if already defined• Can be latent (deferred) if not yet defined• From values in current or path selected registry
– Registery.inject(Object o) for non-Service types– Dependencies defined by @inject property
(possibly setter) annotation
![Page 376: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/376.jpg)
Injection…
• Add @inject(…)– Parameters:• Name: registration name (default: none)• Version: registration version (default: any)• Interface: registration interface (default: field type)• Paths: path to nested registry (ex. “\...\..., \...”)
(default: “.”) ; Like file paths: “.” == current; “..” == parent• DifferedOk: true|false; if true and referenced service is
currently unregistered, the injection will occur later when registration occurs (default true)
![Page 377: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/377.jpg)
Queries
• Allow rich search for services– Each service has a Map<String,Object>– Often using LDAP query syntax to test map– Ex: “””(&(version>=1.5)(test=“xxx”))”””
![Page 378: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/378.jpg)
#Includes
• It is likely that users will define sets of typealias and methodalias statements they want repeatedly used. – Other use cases exist
• So allow them to be stored separately and embedded into a source file– Any line starting “#include” will do this
• Nested #include is allowed; recursive is not
– Ex: #include “/<somepath>/aliases.inc”• #include is not a statement but a preprocessor**
directiveDone by same code that replaces “\uxxxx” values
![Page 379: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/379.jpg)
Additional Features not Defined
Other desired changes not (yet) defined in the JSR set.
![Page 380: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/380.jpg)
LINQ
• Java should have a similar capability• Allow SQL-like queries to be embedded in Java– against 1+ array, collection, XML, datasource, etc.– Allowing direct reference to variables in the
context• Example given List<Map> users, addresses:
var result = select u.name, a.zip from users as u, addresses as a where u.id == a.ownerId;
• Result is a list of tuples/maps of matching
![Page 381: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/381.jpg)
Functional Programming
• Functional programming style enables concurrent programming
• Java has minimal support (thanks to lambdas), it needs a more comprehensive capability– Add more features found in languages like Scala– Support full closures in Java• Variables outside body do not need to be final• Do necessary placement on heap to enable
![Page 382: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/382.jpg)
Dynamic Classes
• Adopt a standard Code Emitting library– Create classes entirely in memory wo/compiler
• Provide a Dynamic ClassLoader– Creates emitted classes from image– Allows explicit release of dynamic classes• Only when 0 instances
![Page 383: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/383.jpg)
Questions?
![Page 384: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/384.jpg)
Thank You
![Page 385: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/385.jpg)
Backmatter (ignore)
![Page 386: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/386.jpg)
Brief Descriptions
![Page 387: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/387.jpg)
Specific Items
• “Operator Overloading”– “Operator” Methods and operator method
mapping– Special behaviors (casts, indexing, call, …)– New Operators– Non-overloading operators– Enhanced initialization– Revised Number hierarchy
• @valuetype – ref type used as value (BigInteger)
![Page 388: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/388.jpg)
Specific Items…
• Import Aliases – allow (generally shorter) aliases for imported symbols
• Terse Imports – select multiple names per import
Enhanced wildcards: * == 0+; + == 1• Scoped Import – allow in any block• Import Blocks – import can have child block• Package Import – import java.util as u
![Page 389: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/389.jpg)
Specific Items…
• Type Aliases – gives a type an alias **• Method Aliases – gives a method an alias **• Field Aliases – @alias (via JavaBeans)• Package literal – java.util.package• Method literal – String.substring(int, int)
**: includes generics
![Page 390: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/390.jpg)
Specific Items…
• List and Map literals – [1,2,3]; {a:1, b:2, c:3}• Collection initialization – new ArrayList()
{1,2,3}• Left-size type inference– Map<> x = {a: 1, b: 2, c; 3}– List<> l = new ArrayList<String>();
![Page 391: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/391.jpg)
Specific Items…
• As - improved instanceof– <T> T as(Class<T> type, Object o) - (T)o or null– <T> void as(Class<T>, Object o, lambda)– Interface Castable<T>; T castTo(Class<T>)
![Page 392: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/392.jpg)
Specific Items…
• Tuple Type – Fixed list– (1, ‘a’, “hello”)– Immutable list; comparable– Fully interoperable with array– Multiple assignment:• (int x, double y, Sting x) = (1, 2.0. “three”);
![Page 393: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/393.jpg)
Specific Items…
• List Type – Functional-style list– 1::2::3.5::”Hello!”::nil– Immutable; change creates new (like String)– Head::tail structure• Functional (vs. Java’s ordered collection)
![Page 394: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/394.jpg)
Specific Items…
• Range Type – concise sequence of values– Immutable; comparable– 1…100; 1..<100; 1>..10; 1…100…2; 10…0…-1– ‘a’…’z’; “aa”…”zz”– for(int i: 0..<100) …; for(1…n) …– “0123456789”[1…3]; “0123456789”[-1…-3];
“0123456789”[-3…-1]; – Over collection: to/from collection
![Page 395: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/395.jpg)
Specific Items…
• Matrix Type – N**-dimension packed array– Bit, any primitive, ref types– aMatrix[1,2,3] = aMatrix[3,2,1]– Supports subviews– Supports per element operations– Supports across matrix operations– Supports concurrent operations
*: at least 10
![Page 396: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/396.jpg)
Specific Items…
• Rational Type – precise representation– int/long/BigInteger sub-types– 1:/3; 3:/5 * 2:/3 == 6:/15; 1:/1 == 1– 1:/0 invalid– Normalized – Fully integrate into Number hierarchy
![Page 397: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/397.jpg)
Specific Items…
• Complex Type – allow imaginary values– Double/BigDecimal real & imag parts– I, I, J, j suffix on imaginary part– 10 + 3.5j; -5j; 10 @ Math.PI/2– 10 == 10 + 0i == 10 - 0i == 10 + -0i– Fully integrate into Number hierarchy
![Page 398: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/398.jpg)
Specific Items…
• Unit Type – Unitized values – prevent mismatches in computations– Base/Derived/Combo Units• Gram/Kilo/Newton (kilo * meter * second ** -2)
– UnitValues• Subclass of Numbers• 10 * newton; Number e = m * C ** 2• 1 * newton + 2 * gram Exception• Fully integrate into Number hierarchy
![Page 399: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/399.jpg)
Specific Items…
• Checked Arithmetic – detect overflows– @checked on class/method
• Power operator - **– Easier then using functions
• Method Binging – Bind method and instance– Allows “currying”; support call; can be async
• Chained Setters – common pattern– New Xxx().abc(1).pqr(2).wyz(3);
![Page 400: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/400.jpg)
Specific Items…
• Pseudo Methods – emulated at run time– Interface Supports; onMissignMethodCall()
• Dymamic variables – duck typing– @dynamic Object duck; duck.quack()
• Var Type – type inferred from initial value– var x =1, name = “barry”, loc = (10, 10);– for(var x: …);
• Default Parameters– int func(int x, var y=2.5, var z=“”) …
![Page 401: Proposals for new function in Java SE 9 and beyond](https://reader035.fdocuments.us/reader035/viewer/2022081519/558de23b1a28ab5b1a8b4612/html5/thumbnails/401.jpg)
Specific Items…
• MORE TBD