Wednesday, March 25, 2009

Extensions Methods In Java!

Note: Oracle has locked down java so this is no longer possible :-(


W00T!

I just added extension methods to java. It's a bit of a hack, but a small bit. (you need to replace the java.lang.Object class)

First, the hack, download and follow the instructions in the readme file of Java_Extensions.zip

Now you can run this test successfully...

package com.spun.util.extensions.tests;
import junit.framework.TestCase;

public class ExtensionsTest extends TestCase
{
public static class MyStringUtils extends ExtendableBase<String>
{
public String removeVowels()
{
StringBuffer b = new StringBuffer();
for (Character c : caller.toCharArray())
{
switch (c)
{
case 'a' :
case 'e' :
case 'i' :
case 'o' :

case 'u' :
break;
default :
b.append(c); } } return b.toString();
}
}
public void testname() throws Exception
{
String name = "Hello World".use(MyStringUtils.class).removeVowels();
assertEquals("Hll Wrld", name);
}
}

Pay extra attention to this line:

"Hello World".use(MyStringUtils.class).removeVowels();

What's more: this use of extensions doesn't have name spacing issues, nor does it pollute all of your objects. It's IDE friendly supporting both code completion and quick fixes!

As a side note, if generics were done better, I would like it to be:

"Hello World".use<MyStringUtils>().removeVowels();

But this is available now! I'll blog more on it tomorrow, but I am very excited about it.