简体   繁体   中英

Java : GroovyClassLoader : cannot find symbol for method in Groovy Class

I am trying to use GroovyClassLoader in java to execute a method in Groovy Class.

I have created a Java Class, pubic method which creates a instance of GroovyClassLoader , parseClass and then creates a new Instance of the class, Calls a method in the class.


public class Gtest{

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

       GroovyClassLoader gcl = new GroovyClassLoader();       

       Class cls =  gcl.parseClass("class Foo { void doIt() { println \"ok\" } }");
       Object obj = cls.newInstance();
       if(obj == null){
           System.out.println("null");
       }
       obj.doIt();


   }
}

Error : Gtest.java:22: error: cannot find symbol obj.doIt(); ^ symbol: method doIt() location: variable obj of type Object 1 error

Its because object class doesn't have doIt() method. You have to use below syntax to invoke your method.

Method sumInstanceMethod
  = Operations.class.getMethod("doIt");
 Object result
      =  sumInstanceMethod.invoke(obj, null);
System.out.println(cls.getDeclaredMethod( "doIt", new Class[] {}).invoke( obj,  new Object[] {} ));

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