Skip to content

Instantly share code, notes, and snippets.

@jonseymour
Created March 6, 2012 06:33
Show Gist options
  • Save jonseymour/1984287 to your computer and use it in GitHub Desktop.
Save jonseymour/1984287 to your computer and use it in GitHub Desktop.
Null and type safe meta data for Java
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