Using generics

1,283 views
Skip to first unread message

tsuraan

unread,
May 28, 2009, 5:23:37 PM5/28/09
to clojure
I have a java class whose constructor expects (among other things) a
BlockingQueue<Long>. It's easy to create a BlockingQueue in clojure
(obviously), but I can't figure out the syntax to specialize it to the
Long type. Is this possible, or does it even make sense? I seem to
recall that generics are just hints for the java compiler and not
actually enforced by the runtime, which would imply that clojure has
no need to support them. Is that the case?

Meikel Brandmeyer

unread,
May 28, 2009, 5:58:13 PM5/28/09
to clo...@googlegroups.com
Hi,

Just ignore the generics. When you say in Java:

BlockingQueue<Long> q = new BlockingQueue<Long>();

you just say in Clojure:

(def q (BlockingQueue.))

Sincerely
Meikel

Stephen C. Gilardi

unread,
May 28, 2009, 6:02:31 PM5/28/09
to clo...@googlegroups.com

I think your conclusion is correct.

Here's an example with java.lang.Class and clojure.contrib.repl-utils/
show:

The Java 1.5 docs for Class.asSubClass show that it takes a generic as
an argument and returns a generic:

<U> Class<? extends U> asSubclass(Class<U> clazz)
Casts this Class object to represent a subclass of the
class represented by the specified class object.

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html

Compare that with the reflection info shown by clojure.contrib.repl-
utils/show:

user=> (show Class)
=== public final java.lang.Class ===
[ 0] static forName : Class (String)
[ 1] static forName : Class (String,boolean,ClassLoader)
[ 2] asSubclass : Class (Class)
[...]
nil
user=> (show Class 2)
#<Method public java.lang.Class
java.lang.Class.asSubclass(java.lang.Class)>

This shows that the entry point is at some level "really" expecting a
Class and returning a Class.

I've done this in practice in a different context and it worked fine.

--Steve

tsuraan

unread,
May 28, 2009, 8:02:23 PM5/28/09
to clo...@googlegroups.com
> user=> (show Class)
> === public final java.lang.Class ===
> [ 0] static forName : Class (String)
> [ 1] static forName : Class (String,boolean,ClassLoader)
> [ 2] asSubclass : Class (Class)
> [...]
> nil
> user=> (show Class 2)
> #<Method public java.lang.Class
> java.lang.Class.asSubclass(java.lang.Class)>
>
> This shows that the entry point is at some level "really" expecting a
> Class and returning a Class.

Yeah, that makes sense. Thanks!

Stuart Sierra

unread,
May 29, 2009, 8:14:05 PM5/29/09
to Clojure
As I understand it, generics aren't "real" types in the JVM. They
don't even exist in the compiled bytecode instructions. They're more
like casting hints to the compiler. When you write List<Long> in
Java, what you get is more like a List<Object> that automatically
casts elements to Long when you retrieve them.
-Stuart Sierra
Reply all
Reply to author
Forward
0 new messages