Issues with generic type detection of SAM types implemented using lambdas
David Lloyd
david.lloyd at redhat.com
Thu Jan 11 14:20:42 UTC 2018
On Thu, Jan 11, 2018 at 8:03 AM, Oliver Gierke <ogierke at pivotal.io> wrote:
>> Am 11.01.2018 um 14:56 schrieb David Lloyd <david.lloyd at redhat.com>:
>>
>> On Thu, Jan 11, 2018 at 3:10 AM, Oliver Gierke <ogierke at pivotal.io> wrote:
>>> Lambda based implementations of SAM types currently don't support inspecting the type for generic type parameters. This can cause unexpected surprise...
>>
>> Here's a non-lambda example that demonstrates that inspecting *any*
>> class for generic type parameters is fragile and not a good idea:
>>
>> public final class Hasher<T> implements ToIntFunction<T> {
>> int applyAsInt(T value) { return value.hashCode(); }
>> }
>>
>> Oops, now all my concrete implementations have generic parameters.
>
> I'm afraid I can't follow.
Your example code which prints the actual type arguments will fail
because there is no actual type argument declared on the generic
*type*, only the *instance*. If you create an API which relies on
getting actual types off of an object instance's class, you've made a
usability mistake.
>> Telling users they cannot have generic parameters on their
>> implementation classes is poor API design.
>
> Who is actually doing that?
"I just wanted to point out that an ordinary user -- in general client
code that uses APIs with SAM types -- *has to implicitly know* whether
*any code* (potentially Java 6 based) downstream might attempt
generics resolution before she can decide whether to use a Lambda with
this SAM type."
Anyone who wrote one of these APIs is actually doing that. It has
nothing to do with lambdas, and everything to do with APIs relying on
the assumption that implementation classes will have actual values for
every type parameter that it may inherit. This assumption is flawed
because it's completely normal for a user to have a single function
implementation that works for many types; this is a solid
memory-conserving technique. The only thing broken by this are
"clever" APIs that require usage of getActualTypeArguments() to get
necessary information from the user.
--
- DML
More information about the compiler-dev
mailing list