简体   繁体   中英

Issue with calling java code from groovy

I have a groovy script source.groovy

#!/usr/bin/env runner
import groovy.sql.Sql
import my.package.MyJavaClass
def String NL = System.getProperty('line.separator')

I run groovy with parameters:

groovy --classpath C:/Projects/myproject/build/classes source.groovy

Where classes is an output folder where ant puts compiled java code. But groovy failse with error

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
C:\Projects\myproject\src\groovy\source.groovy: 12: unable to resolve class my.package.MyJavaClass
 @ line 12, column 1.
   import my.package.MyJavaClass
   ^

1 error

Should I setup any additional parameters to import java files from groovy? Thanks!

Right, given the following directory structure:

.
|-- build
|     |-- classes
|           |-- org
|                 |-- example
|                       |-- Test.class
|-- source.groovy

Where Test.class is built from Test.java :

package org.example ;

public class Test {
    public String getName() {
        return "tim_yates" ;
    }
}

And source.groovy is:

import org.example.Test

println new Test().getName()
println new Test().name

Then, running:

groovy -cp build/classes source.groovy

Prints:

tim_yates
tim_yates

Do you get the same result?

When you run groovy script you need to path classpath (-cp) parameter before all -D options. Otherwise, it is ignored.

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