简体   繁体   中英

How do I convert a java.util.Set[Field] to an Array[Field] in scala?

I am doing some operations using Reflections, between I got to convert a java.util.Set[Field] to Array[Field] and I tried .toArray but getting Array[AnyRef] instead of Array[Field] .

Can anyone help me out in converting java.util.Set to Array preserving the type information?

I'm using version 2.11.7 of Scala

Arrays in Java are not generic , so when you convert from a Java collection it will produce an Array[Object] .

Looking at the documentation of toArray in java.util.Set we find two variations of the method

Object[] toArray()

Returns an array containing all of the elements in this set.

and

<T> T[] toArray(T[] a)

Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array.

You're currently using the first variation, but you can use the second one by passing an array of the correct type as argument.

This is a "workaround" used by Java in order to produce an array of the correct type.

Here's an example

import java.util.HashSet
import java.lang.reflect.Field

val set = new HashSet[Field]
val arr1 = set.toArray // Array[Object]
val arr2 = set.toArray(Array[Field]()) // Array[Field]

Another viable option is to convert your java.util.Set into a scala Set , which provides a "smarter" toArray method:

import java.util.HashSet
import java.lang.reflect.Field
import scala.collection.JavaConversions._

val set = new HashSet[Field]
val arr = set.toSet.toArray // Array[Field]

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