Created
March 6, 2012 06:33
-
-
Save jonseymour/1984287 to your computer and use it in GitHub Desktop.
Null and type safe meta data for Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
given: | |
public class Foo { | |
private String name; | |
private Bar bar; | |
public Foo(String name) | |
{ | |
this.name = name; | |
this.bar = new Bar(name+":bar"); | |
} | |
public String getName() | |
{ | |
return name; | |
} | |
public Bar getBar() | |
{ | |
return bar; | |
} | |
public void setBar(Bar bar) | |
{ | |
this.bar = bar; | |
} | |
} | |
and: | |
public final class FooMeta | |
extends Meta<Foo, FooMeta.Property> | |
{ | |
public enum Property | |
{ | |
bar, | |
name | |
}; | |
public static FooMeta META = new FooMeta(); | |
public static final Getter<Bar> getBar = META.new Getter<Bar>(Property.bar); | |
public static final Setter<Bar> setBar = META.new Setter<Bar>(Property.bar); | |
public static final Getter<String> getName = META.new Getter<String>(Property.name); | |
} | |
then: | |
final Foo foo = ...; | |
final Unary<Foo, String> path = FooMeta.getBar.deref(BarMeta.getName); | |
such that: | |
path.apply(foo) | |
produces almost same output as: | |
foo.getBar().getName(); | |
It is a little better, however, because if foo.getBar() is null, then path.apply(foo) yields null whereas | |
foo.getBar().getName() yields a NullPointerException. | |
The cool thing is that FooMeta can be generated with a reasonably trivial code generation step. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment