Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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[] ???   } } 
like image 314
Kevin Williams Avatar asked Feb 20 '09 18:02

Kevin Williams


People also ask

Can you convert a string to an array?

We can also convert String to String array by using the toArray() method of the List class. It takes a list of type String as the input and converts each entity into a string array.

How do I convert a string to an array of elements?

Way 1: Using a Naive ApproachGet the string. Create a character array of the same length as of string. Traverse over the string to copy character at the i'th index of string to i'th index in the array. Return or perform the operation on the character array.

Can we convert a string to character array in Java?

Java For Testers Now, use the toCharArray() method to convert string to char array. char[] ch = str. toCharArray();


1 Answers

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[] 
like image 73
chanwit Avatar answered Oct 05 '22 22:10

chanwit