TypeResolver tells you what List.get() returns
It's diminishingly rare that I get to write code that improves the internals of both Glazed Lists and Guice...Glazed Lists' BeanProperty
BeanProperty is a convenient utility class that can expose a JavaBeans getter/setter property as its own object. You give it a class (like
Baz.class
) and a property name (like "bar") and it gives you a full property object - you can use it to read and write the property. It even exposes the property's type:class Baz {
private String bar;
String getBar() {
return bar;
}
void setBar(T bar) {
this.bar = bar;
}
}
public void testBaz() {
Baz baz = new Baz();
BeanProperty<Baz> bar = new BeanProperty<Baz>(Baz.class, "bar");
assertEquals(String.class, bar.getValueClass());
bar.set(baz, "hello");
assertEquals("hello", baz.getBar());
}
Eric Burke reported a bug where
BeanProperty
wasn't doing the right thing for generic properties. In this example, we report the value type of Foo.bar as Object.class
rather than String.class
:class Foo<T> {
T getBar();
}
class Baz extends Foo<String> {}
In order to get the return type of
Baz.getBar()
, we need to map Foo's type parameter T
to java.lang.String
.Guice's ProviderMethods
The upcoming release of Guice lets you specify bindings with annotated methods:
class BarProviderMethods {
@Provides @Singleton
Bar provideBar() {
Bar result = new Bar();
result.setBaz("hello");
return result;
}
}
...but we run into problems if users specify generic provider methods. Guice wants to bind the return type of the provider method. Unfortunately, due to generics, that type might be insufficient:
class SetProviderMethods<T> {
@Provides
Set<T> provideSetOfT(T onlyElement) {
return ImmutableSet.of(onlyElement);
}
}
Enter TypeResolver
This class takes a generic type (like
ArrayList<String>
) and exposes precisely what the return types will be: public void testTypeResolver() {
Type listOfString = new TypeLiteral<List<String>>() {}.getType();
Method getMethod = List.class.getMethod("get", int.class);
TypeResolver resolver = new TypeResolver(listOfString);
assertEquals(String.class, resolver.getReturnType(getMethod));
}
I suspect this class is generally useful for any app that uses a reasonable amount of reflection. If this is useful to you, grab the source from Guice SVN.