Hrishikesh Mishra Hrishikesh Mishra - 3 months ago 13
Groovy Question

How to pass java object to groovy method that being called in java?

I'm calling groovy method that take one POJO from java but getting exception.

Here is detail:

File: SampleScript2.groovy

import com.hrishikeshmishra.sb.Obj;

class SampleScript2 {

String process(Obj obj) {
if(obj.num ==10)
return "equal";
else
return "not-equal"
}
}


File: com/hrishikeshmishra/sb/Obj.java

package com.hrishikeshmishra.sb;

class Obj {
public int num;

public Obj(int num) {
this.num = num;
}
}


File: com/hrishikeshmishra/sb/JavaGroovyTest.java

package com.hrishikeshmishra.sb;

import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;

import java.io.File;
import java.io.IOException;


public class JavaGroovyTest {

static final GroovyClassLoader classLoader = new GroovyClassLoader();

public static void main(String[] args) throws IllegalAccessException, IOException, InstantiationException {
example6();
}

private static void example6() throws IOException, IllegalAccessException, InstantiationException {

Class groovy = classLoader.parseClass(new File("/Users/hrishikesh.mishra/hrishi/codes/sb/groovyjava/src/main/resources/SampleScript2.groovy"));
GroovyObject groovyObj = (GroovyObject) groovy.newInstance();
String output = (String) groovyObj.invokeMethod("scriptSays", new Object[] { new Obj(12)});
System.out.println(output);
}
}


Exception:

Exception in thread "main" org.codehaus.groovy.runtime.metaclass.MissingMethodExceptionNoStack: No signature of method: SampleScript2.scriptSays() is applicable for argument types: (com.hrishikeshmishra.sb.Obj) values: [com.hrishikeshmishra.sb.Obj@51931956]

Answer

It's because you're trying to invoke a method called scriptSays(), but the method you've defined is actually called process()...

Comments