Java generics limitations?

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
 
C

Chris Uppal

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.

With the exception of the last three words, you've pretty much got it. Don't
forget that generics have documentary value too, but in terms of the actual
semantics of the language, generics can fairly (if uncharitably) be described
as a complicated, but statically type-safe, way of doing type casts. In the
same vein, C++ templates might be described as an even more complicated, but
statically type-safe[*], way of doing code generation at compile-time.

The two are not similar in anything except syntax.

-- chris

([*] for a different kind of type system)
 
I

Ingo R. Homann

Hi Sean,

perhaps you can do it like this (not tested, no syncronization, ...):

class Singleton
{

static Map<Class, Object> m = new HashMap<Class, Object>();

static <T> T getInstance(Class<T> c) throws InstantiationException,
IllegalAccessException
{
@SuppressWarnings("unchecked")
T o = (T) m.get(c);
if (o == null)
{
o = c.newInstance();
m.put(c, o);
}
return o;
}

}

Ciao,
Ingo
 
T

Thomas Hawtin

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>
{
. . .
};

Why not:

public final class Foo {
private static final Foo instance = new Foo();
public static Foo getInstance() {
return instance;
}
private Foo() {
;
}
...
}

Doesn't seem too difficult. If you don't like all the typing and don't
need a particular base class implementation:

public enum Foo {
INSTANCE;
...
}

Other than enums, I hope you don't have too many singletons.
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?

You have to remember that Java is not C++. Generics are not templates.
Just because some random hack works in C++ doesn't mean it should in
Java. Bashing your head against the wall will just produce poor code.

Java generics are designed to express in the language certain
constraints on types objects interact with. A static equivalent of
polymorphism. That they do that superbly. IMHO, for the job they are
designed to do they wipe the floor with C++ templates.

Tom Hawtin
 
C

Chris Uppal

Thomas said:
Java generics are designed to express in the language certain
constraints on types objects interact with. A static equivalent of
polymorphism. That they do that superbly.

Ah, this is obviously some strange usage of the word superb that I wasn't
previously aware of.

(With apologies to Douglas Adams)

-- chris
 
S

seanwinship

Thomas said:
Why not:

public final class Foo {
private static final Foo instance = new Foo();
public static Foo getInstance() {
return instance;
}
private Foo() {
;
}
...
}

Doesn't seem too difficult.

The point of using a template in C++ is to eliminate the need to do
this for every class that you want to have the behavior.
Other than enums, I hope you don't have too many singletons.

The Singleton pattern is just the simplest example. The Curiously
Recurring Template Idiom has much broader applicability.
You have to remember that Java is not C++. Generics are not templates.
Just because some random hack works in C++ doesn't mean it should in
Java.

It's not a "random hack", it's a useful idiom made possible by the
design of the C++ template mechanism.
Java generics are designed to express in the language certain
constraints on types objects interact with. A static equivalent of
polymorphism. That they do that superbly. IMHO, for the job they are
designed to do they wipe the floor with C++ templates.

That's an interesting claim. As far as I can see, Java generics are
significantly more limited in functionality than are C++ templates and
equal or greater in semantic complexity. How exactly are they wiping
the floor?

Sean
 
D

Dimitri Maziuk

(e-mail address removed) sez:
Thomas Hawtin wrote: ....
The point of using a template in C++ is to eliminate the need to do
this for every class that you want to have the behavior.

Note, however, that if you're exporting a c++ library,
someone has to instantiate every class at link time.
Some compilers are smart enough to do that for you, gcc
wasn't last time I tried (admittedly a while ago).
See also "implicit template instantiation".
That's an interesting claim. As far as I can see, Java generics are
significantly more limited in functionality than are C++ templates and
equal or greater in semantic complexity. How exactly are they wiping
the floor?

Presumably, he has this recurring dream where hunting party
of Java generics wearing janitor clothes rounds up a herd of
c++ templates, grabs 'em by angle brackets...

Dima
 
J

John C. Bollinger

I'm trying to use Java's generics to implement a concept that is
straightforward with C++'s templates.
[...]

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?

What you are missing is that C++ templates and Java generics are
radically different concepts that use similar syntax to solve different,
but overlapping, sets of problems. C++ templates are for creating
multiple classes based on a common pattern; the name "template"
describes this perfectly. Java generics are for expressing type
constraints; the term "generics" describes the form better than the
function. I think there is value in a formal mechanism for expressing
type constraints, and removing the need for casting is not really
central to it. On the other hand, I'm not sure whether I think the
chosen syntax and semantics of Java generics provide a good
value-to-cost ratio.

Anyway, It is no surprise that some things you can do with C++ templates
cannot be done with Java generics. If that bothers you then stick to
C++, or obtain a suitable code generator for Java and pretend that it
works like C++, or just ignore Java generics altogether.
 
S

seanwinship

John said:
Anyway, It is no surprise that some things you can do with C++ templates
cannot be done with Java generics. If that bothers you then stick to
C++, or obtain a suitable code generator for Java and pretend that it
works like C++, or just ignore Java generics altogether.

I'd prefer a more constructive alternative. The effort it obviously
took to implement Java's generics and for developers to learn how to
use them is far out of proportion to the actual value they provide. It
seems that incrementally more effort, with better design goals, could
result in significant additional functionality, perhaps on a par with
C++ templates. Does anyone know if this is being pushed by anyone in
the Java community or being considered by Sun?

Sean
 
D

Dimitri Maziuk

(e-mail address removed) sez:
I'd prefer a more constructive alternative. The effort it obviously
took to implement Java's generics and for developers to learn how to
use them is far out of proportion to the actual value they provide.

Generics are very valuable if you're exporting class libraries:
your client programmers are now getting a compile-time error
instead of a run-time exception (and accompanying support calls)
when they screw up. Plus absence of compile-time type checking
together with the claim Java is the most type-safe language since
Ada made the whole thing look ridiculous.

....It
seems that incrementally more effort, with better design goals, could
result in significant additional functionality, perhaps on a par with
C++ templates. Does anyone know if this is being pushed by anyone in
the Java community or being considered by Sun?

Last I heard they were very interested in cellphone market, and
cellphone people requested object dstruction and non-gc'ed memory
(see RT whitepaper). That's probably coming; as for templates,
there are few more missing pieces required to make those work
(e.g. constructors).

Dima
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

generics puzzle 57
Generics ? 14
Java Generics: limitations? 4
can this be done with generics? 32
Generics 24
limitations on using enum as generic parameter 19
Generics question 6
Hairy generics question 29

Staff online

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,816
Latest member
SapanaCarpetStudio

Latest Threads

Top