Java Magic

by cmur2 on 2012-03-16 in Java

I will describe two uncommon Java phenomenons that hit me short time ago while diving into the fantastic JMonkeyEngine and related stuff.

Local classes

You can declare classes within a method’s body (or exactly anywhere in any block of Java code). They are much like nested classes but remain visible only within the surrounding scope. So if you don’t want to create an anonymous inner class to provide e.g. a callback or some “closure”-like functionality but need a (helper or temporary) object structure just visible within a single method (else use a nested class) you could use a local class to implement this. Stackoverflow has a nice overview of some advantages. Java in a Nutshell has more details on local classes.

public class MyClass {
public static void main(String[] args) {
class LocalClass {
public void echo(String msg) {
new LocalClass().echo("Hi"); // prints "Hi"
// LocalClass is an unrecognized identifier here...

Constructors of anonymous inner classes

You will sooner or later encounter anonymous inner classes for example when working with Swing and having to provide an ActionListener:

new JButton("Click me").addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Oh, you clicked me!");

It’s pretty common to override or implement some methods in such classes but did you ever specified a definition of the constructor for an anonymous inner class? As I learned from here a simple {} will take some code to be executed as the constructor of that class. This allows you to create some kind of not-so-bad looking builder specifications since your constructor code can use the complete API provided by its superclass. The advantages of not having to carry your builder instance in an explicit variable (but implicit via this) and the possibility of simple nesting multiple builders comes with the fact that you will possibly generate a lot of classes in your binary.

new MyDSL() {

In this example MyDSL provides an interface to specify some rendering options of graphical primitives. In context of Nifty GUI this is used for creating complete graphical layouts in Java as the counterpart to their XML definitions for layouts by using several builders.

The post »Java Magic«
is licensed under Creative Commons BY-NC-SA 3.0.