Fwd: 2 new feature proposals: class extensions and import aliases

Behrang Saeedzadeh behrangsa at gmail.com
Sun Sep 21 13:10:27 UTC 2014


Hi all,

This is nothing new as there are other languages that have this feature
already, but now that Java has syntactical support for closures, etc. I
think it would be nice if it was possible to augment classes with custom
methods.

For example, if I wanted to add a method times(Runnable c) to Integer that
runs the given block multiple times so that I could type the following code:

5.times(() -> {
System.out.println("Hello, World");
})


All I needed to do was to define an "extension" for Integer:

*com.foo.IntegerExtension*
*========================*

extension IntegerExtension extends Integer {
 public void times(Runnable r) {
for (int i = this; i < count; i++) {
c.run();
}
}

}

Then I can activate the IntegerExtension explicitly by importing it into a
class:

*com.foo.Main*
*============*

import com.foo.IntegerExtension;

public class Main {
 public static void main(String[] args) {
5.times(() -> {
System.out.println("Hello, World");
})
}
}


Of course this is just to show the idea and the implementation can be quite
different.

Another *very simple* feature that I wish Java had is importing a class
with an alias, similar to Groovy:

import java.util.Date;
import java.sql.Date as SDate;

SDate sDate = ...;
Date date = ...;

// or

import java.awt.Point as Vector;

spaceship.move(new Vector(+5, -10));


What do you fellows think?

Best regards,
Behrang
http://www.behrang.org


More information about the jdk9-dev mailing list