This article is the second part of the Java.next series. In this section, let's look at how the Java.next language interoperate with Java.
In all of these java.next languages, it's easy to interoperate with Java. This is thanks to the Java Virtual Machine specification, which makes it easy for other languages on the JVM to reflect and invoke Java code.
An example of swing
As the first example of Java interoperability, consider creating an application by invoking the Swing API to include:
A window
a button
A modal dialog box pops up when you click the button
As a reference, here's an implementation given with the original Java code:
// Java
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Swing {
public static void main(String[] args) {
JFrame frame = new JFrame("Hello Swing");
JButton button = new JButton("Click Me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JOptionPane.showMessageDialog(null,
String.format(" "Button %s pressed", event.getActionCommand()));
}
});
frame.getContentPane().add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
Next, I'll use the language in Java.next to implement this swing application. For these codes, there are two points to note:
In this example, I render the code in a small to large order based on these languages and Java syntax differences. Doing so allows us to transition from familiar things to unfamiliar things.
The following implementations are not the best practices for these languages. They are deliberately simplified, allowing us to focus our attention on interoperability with Java. In the following articles, I will show more idioms of these languages.
The implementation of groovy
Groovy is the most similar to Java in the Java.next language, and the following is the implementation code for groovy:
// Groovy
import javax.swing.JFrame
import javax.swing.JButton
import javax.swing.JOptionPane
import java.awt.event.ActionListener
frame = new JFrame("Hello Swing")
button = new JButton("Click Me")
button.addActionListener({
JOptionPane.showMessageDialog(null, """ Button ${it.actionCommand} pressed""")
} as ActionListener)
frame.contentPane.add button
frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
frame.pack()
frame.visible = true