Java generics limitations?



I'm trying to use Java's generics to implement a concept that is
straightforward with C++'s templates. The underlying idea is known as
the Curiously Recurring Template Idiom, first described, as far as I
know, by James Coplien. I've used it in C++ to encapsulate generic
behavior like the Singleton pattern:

template <class T> class Singleton
{
private:
static T instance_;

public:
static T& instance() { return instance_; }
};

Using this template, creating a Singleton is simple:

class Foo : public Singleton<Foo>
{
. . .
};

It does not appear to be possible to do this using Java's generics.
Static members in Java are related to the raw generic class rather
than each instantiation of that class. That is, there is only one
instance of instance_ for all Singletons, not one instance each for
Singleton<Foo>, Singleton<Bar>, etc.

I've tried using a Map to maintain an instance for each class used to
parameterize the Singleton, but the getClass() method of Object isn't
static so it can't be called on T.

I'm coming to the conclusion that generics in Java are basically
worthless except as a means of eliminating the need to do some casting
when using collections. Are they really so limited or am I missing
something?

Thanks,

Sean

.



Relevant Pages

  • Re: .NET 2.0 to be launched on Nov 8
    ... native for generics to work. ... > and probably Delphi for Win32 RSN. ... > do when they compile a template, ...
    (borland.public.delphi.non-technical)
  • Re: .NET 2.0 to be launched on Nov 8
    ... One does delegation out ... >> difference in philosophy between generics and templates. ... do when they compile a template, ...
    (borland.public.delphi.non-technical)
  • Re: Cannot apply indexing with [] to an expression of type with ge
    ... template to make me my function work for both types. ... will work with any type that satisfies the constraints. ... compiler doesn't seem to be able to figure it out. ... think you can provide a constraint, thus using generics is not a good idea. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: C++ template tutorial/review : comments welcomed
    ... I agree that the statement about 'unified object model' and 'template ... that of C++ template class, but I have not come seen any papers about it. ... > multiple types into a container, you need to keep track of what type they ... Introducing generics in the CLR ...
    (comp.lang.cpp)
  • Re: inheriting the VC++ template classes into C#.net
    ... C++/CLI using generics. ... template classes into C#.net. ... virtual BOOL OnSetActive() {UpdateData; return ... DTMPOPropertySheet *GetSheet; ...
    (microsoft.public.vc.atl)