Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to simply import a groovy file in another groovy script

Tags:

groovy

~/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

like image 924
Josh Avatar asked Jan 05 '12 05:01

Josh


People also ask

How do I import a Groovy script?

A simple import is an import statement where you fully define the class name along with the package. For example the import statement import groovy. xml. MarkupBuilder in the code below is a simple import which directly refers to a class inside a package.

How do I set the path of a file in Groovy?

Since the path changes machine to machine, you need to use a variable / project level property, say BASE_DIRECTORY, set this value according to machine, here "/home/vishalpachupute" and rest of the path maintain the directory structure for the resources being used.


1 Answers

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.

like image 129
OverZealous Avatar answered Oct 11 '22 05:10

OverZealous