Java Method Handles – The NextGen Reflection

java, java 10, java 11, java 9, java10

Blog post date: 2018-06-10
Relevant Java Versions: Java 7+ (Method Handles were introduced in Java 7)

DukeReflection

Reflection was introduced in Java 1.1 (circa February 1997). Originally introduced as a tool for introspection, it quickly morphed into weapon to examine, introspect as well as alter both behavior and structure of a Java object, bypassing its member accessibility and instantiation rules. This feels very dangerous, and rightfully so, unless the application being built is a framework or a tool that is not fully aware of its operands and needs to dynamically bind such objects and work with/on them intimately.

JSR 292 (https://www.jcp.org/en/jsr/detail?id=292) a.k.a Multi-Language Virtual Machine (MLVM) and code-named: Da Vinci Machine Project, set out ease the implementations of dynamic language implementation and improve their performance, on the JVM. Core features that came to fruition thanks to the JSR:

  1. addition of a new invokedynamic instruction at the JVM level (helped dynamic type checking, the lambda support and performance improvements in other JVM languages, such as JRuby).
  2. ability to change classes and methods at runtime, dynamically (the focus of this blog).

The changes allowed for a lightweight reference to a method. A caller could thus, invoke a method through a method handle without knowing the method’s name, enclosing class, or exact signature, yet the call would run at nearly the speed of a statically linked Java call. These references are called MethodHandles.

API link: https://docs.oracle.com/javase/7/docs/api/java/lang/invoke/MethodHandle.html

Intent

This blog post shows how Method Handles, as a more modern alternate to traditional reflection, can provide similar functionality to what we have come to expect from reflection.

Each section below will act upon a tester class to show how Method Handles work to replace or wrap around reflection calls.

The Invokable Class

The code is located at: https://github.com/c-guntur/reflection/blob/master/src/main/java/none/cgutils/InvokableClass.java.

Below is an excerpt of the code for the class that will be tested using both Reflection and Method Handles:

 1 public class InvokableClass {
 2 
 3     private String name;
 4 
 5     public InvokableClass() {
 6         this.name = "No param InvokableClass constructor";
 7     }
 8 
 9     public InvokableClass(String name) {
10         this.name = name;
11     }
12 
13     public String printStuff(String input) {
14         return "[" + this.name + "] - " + input;
15     }
16 
17     public String publicMethod(String input) {
18         return "[" + this.name + "] - Public method - " + input;
19     }
20 
21     public static String publicStaticMethod(String input) {
22         return "InvokableClass.class - Public static method " + input;
23     }
24 
25     private String privateMethod(String input) {
26         return "[" + this.name + "] - Private method " + input;
27     }
28 
29     protected String protectedMethod(String input) {
30         return "[" + this.name + "] - Protected method " + input;
31     }
32 
33     String packageProtectedMethod(String input) {
34         return "[" + this.name + "] - Package protected method " + input;
35     }
36 }

Invoking the default constructor

The code for default constructor invocation is located at: https://github.com/c-guntur/reflection/blob/master/src/test/java/none/cgutils/DefaultConstructorInvocationTest.java.

Excerpts that matter:

Reflection

 1         String expectedOutput = "[No param InvokableClass constructor] - Default constructor via reflection";
 2 
 3         try {
 4 
 5             Class invokableClassClass = (Class) Class.forName("none.cgutils.InvokableClass");
 6 
 7             InvokableClass invokableClass = invokableClassClass.getDeclaredConstructor().newInstance();
 8 
 9             assertEquals("Reflection invocation failed", expectedOutput, invokableClass.printStuff("Default constructor via reflection"));
10         } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException | ClassNotFoundException e) {
11 
12             fail("reflection failure: " + e.getMessage());
13         }

Method Handles

 1         String expectedOutput = "[No param InvokableClass constructor] - Default constructor via Method Handles";
 2 
 3         // A look-up that can find public methods
 4         MethodHandles.Lookup publicMethodHandlesLookup = MethodHandles.publicLookup();
 5 
 6         // Search for method that: have return type of void (Constructor) and accept a String parameter.
 7         MethodType methodType = MethodType.methodType(void.class);
 8 
 9         try {
10 
11             // Find the constructor based on the MethodType defined above
12             MethodHandle invokableClassConstructor = publicMethodHandlesLookup.findConstructor(InvokableClass.class, methodType);
13 
14             // Create an instance of the Invokable class by calling the exact handle.
15             InvokableClass invokableClass = (InvokableClass) invokableClassConstructor.invokeExact();
16 
17             assertEquals("Method handle invocation failed", expectedOutput, invokableClass.printStuff("Default constructor via Method Handles"));
18         } catch (NoSuchMethodException | IllegalAccessException e) {
19 
20             // findConstructor throws a NoSuchMethodException and an IllegalAccessException,
21             fail("findConstructor failure: " + e.getMessage());
22         } catch (Throwable t) {
23 
24             // invokeExact throws a Throwable (hence catching Throwable separately).
25             fail("invokeExact Failure " + t.getMessage());
26         }

Method Handles Explanation

Line 4: In the Method Handles excerpt, a lookup is setup. A Lookup is a factory to create method handles. A feature of method handles is that access restrictions are checked when the handle is created, rather than when they are used or invoked. This early access check requires that the access be evaluated against some potential caller. The Lookup acts as that caller. For this excerpt, a publicLookup is used (implies there is an alternate for non-public). A publicLookup has minimal access checks (more efficient, scope limited to public methods).

API link: https://docs.oracle.com/javase/7/docs/api/java/lang/invoke/MethodHandles.Lookup.html

Line 7: A MethodType is used to create a signature of the method intended to be looked up. The first parameter represents the return type class while the subsequent parameters (single, array or vararg of class types) represent the method parameters. The MethodType does not associate with the name of the method and is only concerned with types involved. A void return is represented by a void.class. Primitives are represented in a similar manner.

API link: https://docs.oracle.com/javase/7/docs/api/java/lang/invoke/MethodType.html

Line 10: A findConstructor is invoked on the publicLookup created earlier. The parameters are the type on which to find a constructor on, and a MethodType for picking up the right constructor signature.

Line 13: An invokeExact method ensures that the type checks defined in the MethodType are exactly matched. As in indicative by this name there are other similar methods which allow for a some fuzzyness.

API link: https://docs.oracle.com/javase/7/docs/api/java/lang/invoke/MethodHandle.html


Invoking a parameter constructor

The code for parameterized constructor invocation is located at: https://github.com/c-guntur/reflection/blob/master/src/test/java/none/cgutils/ParameteredConstructorInvocationTest.java.

Excerpts that matter:

Reflection

 1         String expectedOutput = "[Constructor Demo] - Constructor via reflection";
 2 
 3         try {
 4 
 5             Class invokableClassClass = (Class) Class.forName("none.cgutils.InvokableClass");
 6 
 7             Constructor invokableClassConstructor = invokableClassClass.getConstructor(String.class);
 8 
 9             InvokableClass invokableClass = invokableClassConstructor.newInstance("Constructor Demo");
10 
11             assertEquals("Reflection invocation failed", expectedOutput, invokableClass.printStuff("Constructor via reflection"));
12         } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
13 
14             fail("reflection failure: " + e.getMessage());
15         }

Method Handles

 1         String expectedOutput = "[Constructor Demo] - Constructor via Method Handles";
 2 
 3         // A look-up that can find public methods
 4         MethodHandles.Lookup publicMethodHandlesLookup = MethodHandles.publicLookup();
 5 
 6         // Search for method that: have return type of void (Constructor) and accept a String parameter.
 7         MethodType methodType = MethodType.methodType(void.class, String.class);
 8 
 9         try {
10 
11             // Find the constructor based on the MethodType defined above
12             MethodHandle invokableClassConstructor = publicMethodHandlesLookup.findConstructor(InvokableClass.class, methodType);
13 
14             // Create an instance of the Invokable class by calling the exact handle, pass in the param value.
15             InvokableClass invokableClass = (InvokableClass) invokableClassConstructor.invokeExact("Constructor Demo");
16 
17             assertEquals("Method handles invocation failed", expectedOutput, invokableClass.printStuff("Constructor via Method Handles"));
18         } catch (NoSuchMethodException | IllegalAccessException e) {
19 
20             // findConstructor throws a NoSuchMethodException and an IllegalAccessException,
21             fail("findConstructor failure: " + e.getMessage());
22         } catch (Throwable t) {
23 
24             // invokeExact throws a Throwable (hence catching Throwable separately).
25             fail("invokeExact Failure " + t.getMessage());
26         }

Method Handles Explanation

Line 7: The MethodType has a return type of void.class (since it is a constructor) and also takes a String.class argument. This call will look for public method signatures of methods that accept a String input parameter and return a void.

Line 13: The invokeExact method has a varargs parameter signature, here a String used by the constructor is passed in


Invoking a public method

The code for public method invocation is located at: https://github.com/c-guntur/reflection/blob/master/src/test/java/none/cgutils/PublicMethodInvocationTest.java.

Excerpts that matter:

Reflection

 1         String expectedOutput = "[No param InvokableClass constructor] - Public method - via reflection";
 2 
 3         try {
 4 
 5             // Find the method on the class via a getMethod.
 6             Method publicMethod = InvokableClass.class.getMethod("publicMethod", String.class);
 7 
 8             InvokableClass invokableClass = new InvokableClass();
 9 
10             assertEquals("Reflection invocation failed", expectedOutput, publicMethod.invoke(invokableClass, "via reflection"));
11         } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
12 
13             fail("reflection failure: " + e.getMessage());
14         }

Method Handles

 1         String expectedOutput = "[No param InvokableClass constructor] - Public method - via Method Handles";
 2 
 3         // A look-up that can find public methods
 4         MethodHandles.Lookup publicMethodHandlesLookup = MethodHandles.publicLookup();
 5 
 6         // Search for method that: have return type of String and accept a String parameter.
 7         MethodType methodType = MethodType.methodType(String.class, String.class);
 8 
 9         try {
10 
11             // Public methods are searched via findVirtual
12             MethodHandle publicMethodHandle = publicMethodHandlesLookup.findVirtual(InvokableClass.class, "publicMethod", methodType);
13 
14             InvokableClass invokableClass = new InvokableClass();
15 
16             assertEquals("Method handles invocation failed", expectedOutput, publicMethodHandle.invoke(invokableClass, "via Method Handles"));
17         } catch (NoSuchMethodException | IllegalAccessException e) {
18 
19             // findConstructor throws a NoSuchMethodException and an IllegalAccessException,
20             fail("findConstructor failure: " + e.getMessage());
21         } catch (Throwable t) {
22 
23             // invoke throws a Throwable (hence catching Throwable separately).
24             fail("invoke Failure " + t.getMessage());
25         }

Method Handles Explanation

Line 10: Public methods are looked up using a findVirtual on the Lookup. The type being looked up, the name of the method and the MethodType (return values, input parameter types) are passed to the findVirtual.


Invoking a public static method

The code for public static method invocation is located at: https://github.com/c-guntur/reflection/blob/master/src/test/java/none/cgutils/PublicStaticMethodInvocationTest.java.

Excerpts that matter:

Reflection

 1         String expectedOutput = "InvokableClass.class - Public static method via reflection";
 2 
 3         try {
 4 
 5             // Find the method on the class via a getMethod.
 6             Method publicStaticMethod = InvokableClass.class.getMethod("publicStaticMethod", String.class);
 7 
 8             assertEquals("Reflection invocation failed", expectedOutput, publicStaticMethod.invoke(InvokableClass.class, "via reflection"));
 9         } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
10 
11             fail("reflection failure: " + e.getMessage());
12         }

Method Handles

 1         String expectedOutput = "InvokableClass.class - Public static method via Method Handles";
 2 
 3         // A look-up that can find public methods
 4         MethodHandles.Lookup publicStaticMethodHandlesLookup = MethodHandles.publicLookup();
 5 
 6         // Search for method that: have return type of String and accept a String parameter.
 7         MethodType methodType = MethodType.methodType(String.class, String.class);
 8 
 9         try {
10 
11             // Public static methods are searched via findStatic
12             MethodHandle publicStaticMethodHandle = publicStaticMethodHandlesLookup.findStatic(InvokableClass.class, "publicStaticMethod", methodType);
13 
14             assertEquals("Method handles invocation failed", expectedOutput, publicStaticMethodHandle.invoke("via Method Handles"));
15         } catch (NoSuchMethodException | IllegalAccessException e) {
16 
17             // findConstructor throws a NoSuchMethodException and an IllegalAccessException,
18             fail("findConstructor failure: " + e.getMessage());
19         } catch (Throwable t) {
20 
21             // invoke throws a Throwable (hence catching Throwable separately).
22             fail("invoke Failure " + t.getMessage());
23         }

Method Handles Explanation

Line 10: Public static methods are looked up using a findStatic on the Lookup. The type being looked up, the name of the public static method and the MethodType (return values, input parameter types) are passed to the findVirtual.


Invoking a private method

The code for private method invocation is located at: https://github.com/c-guntur/reflection/blob/master/src/test/java/none/cgutils/PrivateMethodInvocationTest.java.

Excerpts that matter:

Reflection

 1         String expectedOutput = "[No param InvokableClass constructor] - Private method via reflection";
 2 
 3         try {
 4 
 5             // Cannot call getMethod(), only use getDeclaredMethod to get private and protected methods.
 6             Method privateMethod = InvokableClass.class.getDeclaredMethod("privateMethod", String.class);
 7 
 8             // Method has to be made accessible. Not setting this will cause IllegalAccessException
 9             // Setting accessible to true causes the JVM to skip access control checks
10             privateMethod.setAccessible(true);
11 
12             InvokableClass invokableClass = new InvokableClass();
13 
14             assertEquals("Reflection invocation failed", expectedOutput, privateMethod.invoke(invokableClass, "via reflection"));
15         } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
16 
17             fail("reflection failure: " + e.getMessage());
18         }

Method Handles

 1         String expectedOutput = "[No param InvokableClass constructor] - Private method via Method Handles";
 2 
 3         // A look-up that can find public methods
 4         MethodHandles.Lookup privateMethodHandlesLookup = MethodHandles.lookup();
 5 
 6         try {
 7 
 8             // Rely on old-fashioned reflection.
 9             Method privateMethod = InvokableClass.class.getDeclaredMethod("privateMethod", String.class);
10 
11             privateMethod.setAccessible(true);
12 
13             // Unreflect to create a method handle from a method
14             MethodHandle privateMethodHandle = privateMethodHandlesLookup.unreflect(privateMethod);
15 
16             InvokableClass invokableClass = new InvokableClass();
17 
18             assertEquals("Method handles invocation failed", expectedOutput, privateMethodHandle.invoke(invokableClass, "via Method Handles"));
19         } catch (NoSuchMethodException | IllegalAccessException e) {
20 
21             // findConstructor throws a NoSuchMethodException and an IllegalAccessException,
22             fail("findConstructor failure: " + e.getMessage());
23         } catch (Throwable t) {
24 
25             // invoke throws a Throwable (hence catching Throwable separately).
26             fail("invoke Failure " + t.getMessage());
27         }

Method Handles Explanation

Line 4: Private methods can be looked up via lookup method call that has larger find radius than the publicLookup (i.e public as well as private/protected lookup).

Line 8: There is no equivalent to finding private methods, thus reflection is still needed to get to a Method instance of the private method. As with reflection, private method instances can only be invoked only after a setAccessible is set to true.

Line 11: Private method instances looked up via reflection need to be “unreflected” to convert from the java.lang.reflect.Method to java.lang.invoke.MethodHandle. There is no direct find equivalent for private methods.


Invoking a protected method

The code for protected method invocation is located at: https://github.com/c-guntur/reflection/blob/master/src/test/java/none/cgutils/ProtectedMethodInvocationTest.java.

Excerpts that matter:

Reflection

 1         String expectedOutput = "[No param InvokableClass constructor] - Protected method via reflection";
 2 
 3         try {
 4             // Cannot call getMethod(), only use getDeclaredMethod to get private and protected methods.
 5             Method protectedMethod = InvokableClass.class.getDeclaredMethod("protectedMethod", String.class);
 6 
 7             // Method has to be made accessible. Not setting this will cause IllegalAccessException
 8             // Setting accessible to true causes the JVM to skip access control checks
 9             protectedMethod.setAccessible(true);
10 
11             InvokableClass invokableClass = new InvokableClass();
12 
13             assertEquals("Reflection invocation failed", expectedOutput, protectedMethod.invoke(invokableClass, "via reflection"));
14         } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
15 
16             fail("reflection failure: " + e.getMessage());
17         }

Method Handles

 1         String expectedOutput = "[No param InvokableClass constructor] - Protected method via Method Handles";
 2 
 3         // A look-up that can find public methods
 4         MethodHandles.Lookup protectedMethodHandlesLookup = MethodHandles.lookup();
 5 
 6         try {
 7             // Rely on old-fashioned reflection.
 8             Method protectedMethodMethod = InvokableClass.class.getDeclaredMethod("protectedMethod", String.class);
 9             protectedMethodMethod.setAccessible(true);
10             // Unreflect to create a method handle from a method
11             MethodHandle protectedMethodHandle = protectedMethodHandlesLookup.unreflect(protectedMethodMethod);
12 
13             InvokableClass invokableClass = new InvokableClass();
14 
15             assertEquals("Reflection invocation failed", expectedOutput, protectedMethodHandle.invoke(invokableClass, "via Method Handles"));
16         } catch (NoSuchMethodException | IllegalAccessException e) {
17 
18             // findConstructor throws a NoSuchMethodException and an IllegalAccessException,
19             fail("findConstructor failure: " + e.getMessage());
20         } catch (Throwable t) {
21 
22             // invoke throws a Throwable (hence catching Throwable separately).
23             fail("invoke Failure " + t.getMessage());
24         }

Method Handles Explanation

Line 4: Protected methods can be looked up via lookup method call that has larger find radius than the publicLookup (i.e public as well as private/protected lookup).

Line 8: There is no equivalent to finding protected methods, thus reflection is still needed to get to a Method instance of the protected method. As with reflection, protected method instances can only be invoked only after a setAccessible is set to true.

Line 11: Protected method instances looked up via reflection need to be “unreflected” to convert from the java.lang.reflect.Method to java.lang.invoke.MethodHandle. There is no direct find equivalent for protected methods.


Invoking a package-protected method

The code for package-protected method invocation is located at: https://github.com/c-guntur/reflection/blob/master/src/test/java/none/cgutils/PackageProtectedMethodInvocationTest.java.

Excerpts that matter:

Reflection

 1         String expectedOutput = "[No param InvokableClass constructor] - Package protected method via reflection";
 2 
 3         try {
 4 
 5             // Cannot call getMethod(), only use getDeclaredMethod to get private and protected methods.
 6             Method packageProtectedMethod = InvokableClass.class.getDeclaredMethod("packageProtectedMethod", String.class);
 7 
 8             // Method has to be made accessible. Not setting this will cause IllegalAccessException
 9             // Setting accessible to true causes the JVM to skip access control checks
10             packageProtectedMethod.setAccessible(true);
11 
12             InvokableClass invokableClass = new InvokableClass();
13 
14             assertEquals("Reflection invocation failed", expectedOutput, packageProtectedMethod.invoke(invokableClass, "via reflection"));
15         } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
16 
17             fail("reflection failure: " + e.getMessage());
18         }

Method Handles

 1         String expectedOutput = "[No param InvokableClass constructor] - Package protected method via Method Handles";
 2 
 3         // A look-up that can find public methods
 4         MethodHandles.Lookup packageProtectedMethodHandlesLookup = MethodHandles.lookup();
 5 
 6         try {
 7             // Rely on old-fashioned reflection.
 8             Method packageProtectedMethod = InvokableClass.class.getDeclaredMethod("packageProtectedMethod", String.class);
 9             packageProtectedMethod.setAccessible(true);
10 
11             // Unreflect to create a method handle from a method
12             MethodHandle packageProtectedMethodHandle = packageProtectedMethodHandlesLookup.unreflect(packageProtectedMethod);
13 
14             InvokableClass invokableClass = new InvokableClass();
15 
16             assertEquals("Reflection invocation failed", expectedOutput, packageProtectedMethodHandle.invoke(invokableClass, "via Method Handles"));
17         } catch (NoSuchMethodException | IllegalAccessException e) {
18 
19             // findConstructor throws a NoSuchMethodException and an IllegalAccessException,
20             fail("findConstructor failure: " + e.getMessage());
21         } catch (Throwable t) {
22 
23             // invoke throws a Throwable (hence catching Throwable separately).
24             fail("invoke Failure " + t.getMessage());
25         }

Method Handles Explanation

Line 4: Package-protected methods can be looked up via lookup method call that has larger find radius than the publicLookup (i.e public as well as private/protected lookup).

Line 8: There is no equivalent to finding package-protected methods, thus reflection is still needed to get to a Method instance of the package-protected method. As with reflection, package-protected method instances can only be invoked only after a setAccessible is set to true.

Line 11: Package-protected method instances looked up via reflection need to be “unreflected” to convert from the java.lang.reflect.Method to java.lang.invoke.MethodHandle. There is no direct find equivalent for package-protected methods.


There are a few other cool methods that will be covered in a subsequent blog.

Method Handles – Enhancements in Java Versions

    1. JSR-292https://www.jcp.org/en/jsr/detail?id=292Java 1.7 – Method Handles introduction.
    1. JEP-160http://openjdk.java.net/jeps/160Java 1.8 – Method Handles enhancements:
      • Improve performance, quality, and portability of method handles and invokedynamic.
      • Reduce the amount of assembly code in the JVM.
      • Reduce the frequency of native calls and other complex transitions of control during method handle processing.
      • Increase the leverage on JSR 292 performance of existing JVM optimization frameworks.
      • Remove low-leverage or complex structures from the JVM that serve JSR 292 only. (E.g., remove the pattern-matching “method handle walk” phase.)
      • Complete compatibility with the Java SE 7 specification for JSR 292.
      • A better reference implementation of JSR 292.
    1. JEP-274http://openjdk.java.net/jeps/274Java 9 – Method Handles enhancements (many API additions):
      • In the MethodHandles class in the java.lang.invoke package, provide new MethodHandle combinators for loops and try/finally blocks.
      • Enhance the MethodHandle and MethodHandles classes with new MethodHandle combinators for argument handling.
      • Implement new lookups for interface methods and, optionally, super constructors in the MethodHandles.Lookup class.

Complete Github project link: https://github.com/c-guntur/reflection

That’s a wrap on Java Method Handles – The NextGen Reflection (with more in a subsequent blog). Hope this post was helpful.

Switching between multiple JDKs on a Mac

java, java 10, java 11, java 8, java 9, technology

Blog post date: 2018-May-18
Relevant versions of Java: Java 1.7, 8, 9, 10, 11

We often work with different versions of Java. There are times when we would like to test our application/program against different JDKs. Or … we just love to collect all versions of Java released just to show off.

Either of these would mean some kind of control of the JAVA_HOME and the PATH environment variables.

MultiDuke

Many developers have successfully overcome this with innovative scripts to quickly switch Java versions. I am one such developer and below is an explanation of my setup.

Current installations of JDK on my Mac:

  • JDK 1.7.0_80
  • JDK 1.8.0_172
  • JDK 9.0.4
  • JDK 10.0.1
  • JDK 11-ea+14

How does one determine the current installations of JDK?

On your Mac terminal run the command:

/usr/libexec/java_home -verbose

Sample output:

Matching Java Virtual Machines (5):
11, x86_64: "OpenJDK 11-ea" /Library/Java/JavaVirtualMachines/jdk-11.jdk/Contents/Home
10.0.1, x86_64: "OpenJDK 10.0.1" /Library/Java/JavaVirtualMachines/jdk-10.0.1.jdk/Contents/Home
9.0.4, x86_64: "OpenJDK 9.0.4" /Library/Java/JavaVirtualMachines/jdk-9.0.4.jdk/Contents/Home
1.8.0_172, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_172.jdk/Contents/Home
1.7.0_80, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_80.jdk/Contents/Home

Simple ! Quite easy to determine the current JDKs available.

How can I switch Java versions easily?

Aliases. That’s it. If you know this, you can skip the remaining part of this blog. What is really cool is how a single JVM exec command can be used to switch JDK versions.

Sharing an excerpt from a .bash_profile:


alias jdk11="export JAVA_HOME=`/usr/libexec/java_home -v 11` && export PATH=$JAVA_HOME/bin:$PATH; java -version"
alias jdk10="export JAVA_HOME=`/usr/libexec/java_home -v 10` && export PATH=$JAVA_HOME/bin:$PATH; java -version"
alias jdk9="export JAVA_HOME=`/usr/libexec/java_home -v 9` && export PATH=$JAVA_HOME/bin:$PATH; java -version"
alias jdk8="export JAVA_HOME=`/usr/libexec/java_home -v 1.8` && export PATH=$JAVA_HOME/bin:$PATH; java -version"
alias jdk7="export JAVA_HOME=`/usr/libexec/java_home -v 1.7` && export PATH=$JAVA_HOME/bin:$PATH; java -version"

Note how the Java versioning from 9 onwards is a full digit? The same applies with the default directory names of the installed JDKs. This was a deliberate change toshake off the 1.x naming style of prior versions of Java.

JDK switching output

A picture would do this more justice.
Switching JDKs at Terminal

Maintenance of JDKs

Needs Admin rights on the Mac !

Keeping the JDK versions up-to-date is in everyone’s best interest, both for the new features as well as any security patches. A few steps that can help with maintaining:

    1. Extract the latest build/patch of the JDK into the directory: /Library/Java/JavaVirtualMachines.
      • If an installer was used, most likely the directories are created.
      • If a tarball was extracted from, make sure to move the extracted directory under the parent mentioned above.

 

    1. Post-installation, open a new terminal shell (current shell will not pick up the latest patch of an existing version of the JDK).
      • Add the appropriate alias, if this is a new version of Java
      • If existing version being patched, then no further action is needed.

 

    1. Type in the appropriate alias and verify that the build/patch is what shows.

 

  1. Once verified, the options for removing the prior patch present themselves:
    • delete older build/patch since it is no longer useful to reclaim space.
    • retain older build/patch, for other usage. It is possible to manually switch to this build/patch:
      • export JAVA_HOME=/Library/Java/JavaVirtualMachines/
      • export PATH=$JAVA_HOME/bin:$PATH

That’s a wrap on Switching JDKs on a Mac. Hope this post was helpful.

Java 9 Features – Changes to Optional

java, java 9, technology

Duke-Java9

In Java 8, a new class named Optional was introduced. Or rather in the word-style of Douglas Adams, “in the beginning null was created. This made a lot of people angry and was widely regarded as a bad move“. Optional was introduced to alleviate some of that anger.

Optional relieved developers of the grief of null checks and the “fun” of a NullPointerException popping up when failing to null check.

In Java 8, the Optional already had very useful methods:

  • of – Wrap the non-null value into an Optional.
  • ofNullable – Wrap and return an Optional of the current value, if current value is null, return Optional.empty()
  • isPresent – Checks and returns a boolean indicating the presence of a non-null value in the Optional.
  • ifPresent – Checks and invokes the specified Consumer instance upon the presence of a non-null value in the Optional.
  • get – Fetch the value in the Optional if it is not null, else throw a NoSuchElementException
  • orElse – Fetch the value in the Optional if it is not null, else return the other element passed in.
  • orElseGet – Fetch the value in the Optional if it is not null, else return invoke the other Supplier to fetch an element instead.
  • orElseThrow – Fetch the value in the Optional if it is not null, else throw the passed in Exception.
  • filter – If the value exists, test the filtering Predicate on it and if true return result wrapped in an Optional, else return Optional.empty().
  • map – If the value exists, apply the mapping Function to it and return any non-null result wrapped in an Optional, else return Optional.empty().
  • flatMap – If the value exists, apply the Optional-bearing mapping Function to it and return any non-null result wrapped in an Optional, else return Optional.empty().

Java 9 changes

  • ifPresentOrElse – Checks and returns a boolean indicating the presence of a non-null value in the Optional, or else, invokes the Runnable action.
  • or – Wrap and return an Optional of the current value if not null; if current value is null, return Optional by invoking the specified Supplier
  • stream – Returns a sequential stream containing only the value, if the value is non-null.

Optional::ifPresentOrElse

Consider a situation where the code is to either run a Consumer if the value exists or else run a different action. This is not possible in the Java 8 Optional behavior. Optional in Java 8 provides an orElse or an orElseGet method, both of which actually return an unwrapped value, rather than act as an execution block.

Source at: https://github.com/c-guntur/java9-examples/blob/master/src/test/java/samples/java9/optional/OptionalIfPresentOrElse.java

Pre-Java 8 :


if(preference != null) { 
    callPresenceAction();
} else {
    callAbsenceAction();
}

In Java 8 :


if(optionalPreference.isPresent()) { 
    callPresenceAction();
} else {
    callAbsenceAction();
}

or


optionalPreference.ifPresent(callPresenceConsumer());
// orElseGet returns a non-optional value
// it cannot be used to simply execute an action.
Preference p = optionalPreference.orElseGet(callAbsenceSupplier());

In Java 9 :


optionalPreference
        .ifPresentOrElse(presenceAction,absenceAction);

Optional::or

Per the Java 8 API, both the orElse and the orElseGet do not return an Optional, rather return the unwrapped value. It is possible that such a value is null. The or method is introduced as a means to execute a supplier on absence of an unwrapped value in the container, and returns an Optional, rather than the unwrapped value.

Source at: https://github.com/c-guntur/java9-examples/blob/master/src/test/java/samples/java9/optional/OptionalOr.java

Pre-Java 8 :


Preference preference = findPreference(name); 
if(preference == null) {
    preference = createPreference(name, description);
}
// preference can still be null !!!

In Java 8 :


Preference preference = 
        findOptionalPreference(name)
            .orElseGet(getPreferenceSupplier(name, description));
// preference can still be null !!!

In Java 9 :


Optional optionalPreference = 
        findOptionalPreference(name)
            .or(getOptionalPreferenceSupplier(name, description));
// optional preference, so, protected from being null !!!

Optional::stream

Given a situation where a stream or collection of Optionals exist, and we need to extract values from each, if they contain non-null values. Optional::stream returns a stream with a single non-null value if the Optional has a non-null value, or returns an empty stream otherwise.

Source at: https://github.com/c-guntur/java9-examples/blob/master/src/test/java/samples/java9/optional/OptionalStream.java

Pre-Java 8 :


List preferences = new ArrayList();
for (String preferenceName : PREFERENCE_NAMES) {
    Preference aPreference = findPreference(preferenceName);
    if (aPreference != null) {
        preferences.add(aPreference);
    }
}

In Java 8 :


List preferences =
        PREFERENCE_NAMES.stream()
                .map(preferenceName -> findOptionalPreference(preferenceName))
                .filter(Optional::isPresent)
                .map(Optional::get)
                .collect(toList());

In Java 9 :


List preferences =
        PREFERENCE_NAMES.stream()
                .map(preferenceName -> findOptionalPreference(preferenceName))
                .flatMap(Optional::stream)
                .collect(toList());

That’s a wrap on the Optional changes in Java 9. Hope this post was helpful.

Java 9 Features – Private Interface Methods

java, java 9, technology

Duke-Java9

A blog on Java 9 changes for interfaces.

Evolution of interfaces in Java:

Until Java 7, all versions of Java maintained the same set of features for interfaces. Interfaces can

Interfaces contained method signatures and were useful for storing public constants. Since then, constants have remained a staple of the interface. Recent changes have been more focused on methods.

Java 7

  • abstract methods – Method signatures as contracts that had to be implemented by the class that implemented the interface.

Java 8

  • default methods – Methods with an implementation in the interface, providing an option to the implementing class to override.

    This change allowed for extension and growth of existing APIs without major refactoring and without harming backward-compatibility. Best example of this is the Java 8 collection framework that introduced new features on the root interfaces without having to make significant changes to any of the implementations.

    See http://docs.oracle.com/javase/8/docs/api/java/util/List.html for sort(...) or spliterator() or replaceAll(...).

  • static methods – Methods with the static modifier with an implementation, which thus belong to the interface.

    These methods cannot be overwritten in implementing classes. Adding static methods allows the interface to control some behavior without allowing for an implementation to alter such behavior.

    See http://docs.oracle.com/javase/8/docs/api/java/util/Map.Entry.html for comparingByKey() or comparingByValue().

Java 9

  • private methods – Methods with implementation in the interface that remain private to the interface alone.

    These methods are useful from an encapsulation perspective to hold some logic that the implementations should not override.

    While there is no concrete example in the JDK API that I could immediately find, there are several existing interfaces which have workarounds for encapsulating private methods via private inner classes. Such workarounds can be circumvented with private methods.

Java support in interfaces

  Java 7 Java 8 Java 9
constants
abstract methods
default methods
public static methods
private methods
private static methods

Modifier combinations in Java 9

Combination Comment
[public] (naturally abstract) supported
[public] default supported
[public] static supported
private supported
private static supported
private abstract compile-time error
private default compile-time error