Static fields in specialized classes

Vitaly Davidovich vitalyd at gmail.com
Mon Oct 13 19:09:18 UTC 2014


As a user, I would *not* expect that there's just one fooCount field for
all Foo<T> instances.  Maybe this is because I also know .NET, where a
static field in a generic type is "replicated" into all closed types over T
(granted, generics are reified there, but if java were to reify or
specialize, then I don't see anything wrong with replicating the statics
into the specializations).

And yes, putting statics into generic classes is frowned upon.  In fact,
tools like Resharper will warn about such occurrences.

On Mon, Oct 13, 2014 at 2:46 PM, Brian Goetz <brian.goetz at oracle.com> wrote:

> Regardless of whether our implementation is by specialization or
>>> erasure (or both), logically there is just *one* field 'x' for any
>>> instantiation Foo<T>.
>>>
>>
>> How sure are you that this is true?  What if the type of static final
>> x happens to be “T”? (nonsensical when erased, but not when reified)
>>
>
> Currently the rules still prohibit T to appear in member signatures, so
> that's currently a non-issue, but there are potential surprising behaviors
> in either direction, and the question is which interpretation is less
> surprising.
>
> Consider this:
>
> class Foo<any T> {
>     static int fooCount;
>
>     public void foo() {
>         ++fooCount;
>     }
> }
>
> Based on how generics have worked since 2004, users will expect that there
> is one fooCount field that is incremented each time foo() is called on any
> instance of a Foo<T>.  Having only some Foo<T> instances participate in
> this game, but not others, would be surprising.
>
> Stepping back, statics are the root of much evil in Java in the first
> place.  So, while one could build a more generalized notion of statics in
> the context of reified generics as you suggest, I'm inclined to politely
> decline that option.
>
>
>


More information about the valhalla-dev mailing list