How do I convert a Groovy String collection to a Java String Array?

GroovyCollections

Groovy Problem Overview


I'm trying to call a methond on a Java class from a Groovy class. The Java method has a String array as a parameter, and I have a collection of Strings in my Groovy class. How do I convert the Groovy collection to a Java String array?

Java Method:

public class SomeJavaClass{
  public void helpDoSomething(String[] stuff){

  }
}

Groovy code

class SomeGroovyClass {
  def data = ["a", "b", "c"]

  def doSomething = {
    def javaClass = new SomeJavaClass()
    javaClass(data) //Groovy passes ArrayList, Java class expects String[] ???
  }
}

Groovy Solutions


Solution 1 - Groovy

To be correct, def data = ["a","b","c"] it is a List, not an array.

Just try casting like this:

def data = ["a","b","c"] as String[]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKevin WilliamsView Question on Stackoverflow
Solution 1 - GroovychanwitView Answer on Stackoverflow