首页 文章

Groovy:无法解析课程

提问于
浏览
4

当我通过命令行或Jenkins运行我的Groovy脚本时,我收到“无法解析类”错误 .

我在C:\ Users \ myuser \ git \ productname \ mycompany-build \ src \ main \ groovy \ com \ mycompany \ build中的同一文件夹中有以下2个groovy文件

Foo.groovy

package com.mycompany.build

class Foo {

  Foo() {
  }

  public void runBar() {
    Bar bar = new Bar();
    bar.name = "my name";
    System.out.println(bar.name);
  }

  static void main(String[] args) {
    Foo foo = new Foo();
    foo.runBar()
  }
}

Bar.groovy

package com.mycompany.build

class Bar {
  String name;
}

我使用命令行运行Foo.groovy .

运行Groovy时,我位于以下目录中:

C:\Users\myuser\git\productname\mycompany-build\src\main\groovy\com\mycompany\build

这是我在命令行(cmd)上输入的内容:

C:/java/tools/groovy-2.4.11/bin/groovy -cp C:/Users/myuser/git/myproject/mycompany-build/src/main/groovy/com/mycompany/build Foo.groovy

我得到以下内容,它无法找到类“Bar”,但Bar.groovy文件与Foo.groovy位于同一目录中,更不用说我也指定了-cp .

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
C:\Users\myuser\git\myproject\mycompany-build\src\main\groovy\com\mycompany\build\Foo.groovy: 9: unable to resolve class Bar
 @ line 9, column 9.
       Bar bar = new Bar();
           ^

C:\Users\myuser\git\myproject\mycompany-build\src\main\groovy\com\mycompany\build\Foo.groovy: 9: unable to resolve class Bar
 @ line 9, column 15.
       Bar bar = new Bar();
                 ^

2 errors

你能告诉我如何从命令行运行它吗?

一旦我能够运行,我计划在Jenkins工作中运行它 . 我开始尝试在Jenkins的工作中运行它,但得到了同样的问题,这使我首先看到它从命令行运行它 .

我确实尝试使用正斜杠和反斜杠,但行为没有区别 .

3 回答

  • 3

    您在类路径和包使用中的问题 .

    让它工作

    1. 如果您的类在包 com.mycompany.build 中声明,则groovy / java将在文件夹 com/mycompany/build 中查找它到classpath . 所以你需要从类路径中排除package-folders:

    groovy -cp C:\Users\myuser\git\productname\mycompany-build\src\main\groovy Foo.groovy
    

    2. 您可以删除这两个类中的包声明 . 在这种情况下,groovy / java将在类路径中查找没有package-folder前缀的类: C:\Users\myuser\git\productname\mycompany-build\src\main\groovy\com\mycompany\build 并且您的命令应该有效 . 如果您当前的文件夹是具有groovy类的文件夹,那么命令可能更简单:

    groovy -cp . Foo.groovy
    
  • 1

    根据docs,在类路径中,您只能拥有.jar,.zip和.class文件 . 类Bar不能被解析,因为它是.java文件,而不是 compiled Java类(.class) .

    以下适用于我:

    C:/java/tools/groovy-2.4.11/bin/groovyc Bar.groovy
    C:/java/tools/groovy-2.4.11/bin/groovy Foo.groovy
    my name
    

    另请注意,由于Bar.class与Foo.groovy位于同一文件夹中,因此您无需指定类路径 .

  • 0

    我想你只需要将classpath参数设置为包含类的目录,即 productname 而不是 myproject

    C:/java/tools/groovy-2.4.11/bin/groovy -cp C:\Users\myuser\git\productname\mycompany-build\src\main\groovy\com\mycompany\build Foo.groovy
    

相关问题