1

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

8
  • 1
    Cannot reproduce: import java.lang.reflect.Field; def test(in: Set[Field]): Array[Field] = in.toArray Commented Jul 21, 2015 at 13:09
  • @ 0__ ... I am getting type mismatch error since it is java.util.Set Commented Jul 21, 2015 at 13:19
  • @Jet You should add that to the question. Commented Jul 21, 2015 at 13:27
  • I recommend to use Scala collections not Java collections Commented Jul 21, 2015 at 13:49
  • @0__ ..Actually my annotation is in Java. So I am getting Java collections. Commented Jul 21, 2015 at 13:50

1 Answer 1

4

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.