简体   繁体   中英

How to call java method taking parameter as List<Class<?>> from Scala

I am trying to call a java method which takes List<Class<?>> from scala .

The compilation fails with

type mismatch;
 found   : java.util.List[Class[T]] where type T <: Person.type
 required: java.util.List[Class[_]]

I tried using JavaConverters but get the same error.

Java method:

void registerClasses(List<Class<?>> var1);

Calling from Scala:

def registerEntities() = registry.registerClasses(List(Person.getClass).asJava)

The problem is that the inferred type for Person.getClass is not the one you want. You need to specify the expected type, and this can be done by an explicit type parameter

registry.registerClasses(List[Class[_]](Person.getClass).asJava)

(I don't understand why type ascription doesn't work here:

registerClasses(List(Person.getClass: Class[_]).asJava)

type mismatch;
 found   : java.util.List[Class[_$2]] where type _$2
 required: java.util.List[Class[_]]
Note: Class[_$2] <: Class[_], but Java-defined trait List is invariant in type E.
You may wish to investigate a wildcard type such as `_ <: Class[_]`. (SLS 3.2.10)

So far as I can tell it should.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM