S
seanwinship
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
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