Josh
Josh

Reputation: 153

how to simply import a groovy file in another groovy script

~/groovy
 % tree
.
├── lib
│   ├── GTemplate.class
│   └── GTemplate.groovy
└── Simple.groovy


class GTemplate {
  static def toHtml() {
    this.newInstance().toHtml1()
  }
  def toHtml1() {
    "test"
  }
}


import lib.*
class Simple extends GTemplate {
}

Error:

% groovyc Simple.groovy org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: Compilation incomplete: expected to find the class lib.GTemplate in /home/bhaarat/groovy/lib/GTemplate.groovy, but the file contains the classes: GTemplate 1 error

Upvotes: 6

Views: 35704

Answers (1)

OverZealous
OverZealous

Reputation: 39560

It looks like you are confusing Groovy with PHP-like techniques.

Because it's closer to Java, if a class exists within a subfolder, it needs to exist within a package of the same name. In your example, you could add this line to the top of GTemplate.groovy and recompile the file:

package lib

However, this means that the fully-qualified name for GTemplate is now actually lib.GTemplate. This may not be what you want.

Alternatively, if you want to use the files from a subfolder without using packages, you could remove the import statement from Simple.groovy, and instead compile and run the class like so:

groovyc -classpath $CLASSPATH:./lib/ Simple.groovy
groovy -classpath $CLASSPATH:./lib/ Simple

NOTE: If you don't have a CLASSPATH already set, you can simply use:

groovyc -classpath ./lib/ Simple.groovy
groovy -classpath ./lib/ Simple

Also, for windows machines, change $CLASSPATH: to %CLASSPATH%;

I strongly recommend learning about packages and understanding how they work. Look at this Wikipedia article on Java packages for a starting point.

Upvotes: 12

Related Questions