Lambda expression as a succinct way to pass in type parameter
Zhong Yu
zhong.j.yu at gmail.com
Mon Nov 14 09:29:07 PST 2011
Hi Brian, I think I have an interesting use case, but I need your
confirming that it's viable. Consider a method
<T> T foo() {...}
Suppose the body of foo() needs to know the runtime value of T, due to
erasure, we must pass in a construct containing the value of T
<T> T foo(TypeToken<T> type) {...}
interface TypeToken<T>
{
int f(int x); // not really used
}
We can call foo() this way
Bar result = foo(x->x);
The lambda expression x->x is compiled into an object of
TypeToken<Bar>, and the body of foo() can use reflection to retrieve
T=Bar.
// equivalent code
Bar result = foo(type);
static TypeToken<Bar> type = new TypeToken<Bar>(){ public int
f(int x){ return x; } }
Question: do you see anything wrong with this usage pattern? (other
than how odd it looks)
cheers,
Zhong Yu
More information about the lambda-dev
mailing list