Parameterized Types

Tal Liron tal.liron at threecrickets.com
Wed Oct 28 01:10:23 UTC 2015


You answered your own question: the Java compiler "erases" these types, 
so they are not available to you. It's purely a Java compiler feature, 
not part of the JVM.

However, JavaScript can provide a workaround. Just create your own 
wrapper (a JavaScript dict) that includes custom type information:

var myList = {};
myList.list = new java.util.ArrayList();
myList.type = String;

You can then can create JavaScript functions that check for the type and 
then delegate to this.list:

myList.add = function(value) {
   if (!(value instanceof this.type) throw 'Wrong!';
   this.list.add(value);
}

Note that if you want to use JavaScript (as opposed to JVM) types, you 
must explicitly use their constructor:

myList.add(new String('this will work'))
myLast.add('this won't work')

On 10/27/2015 06:48 PM, James Falkner wrote:
> Hey all,
>
> Currently @ JavaOne enjoying the Nashorn talks. But I have a question. 
> Is it possible to create extended classes using parameterized types?
>
> What I want to do is create these:
>
> class SomeClass extends SomeBaseClass<SomeType> {
> ...
> }
>
> I know parameterized types are mostly a compile-time thing, but they 
> are encoded into the class bytes and can be accessed in Java using:
>
> ParameterizedType t =  (ParameterizedType) clazz.getGenericSuperclass();
> Type[] types = parameterizedType.getActualTypeArguments();
>
> So I was wondering if it was possible to instantiate a concrete Java 
> class from Javascript such that it would appear just as though I had 
> created it as above?
>
> Using Java.type() and Java.extend() doesn't seem to create the class 
> in the same way as the Java code with Parameterized types. Thanks!
>
> -James
>



More information about the nashorn-dev mailing list