Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access a java class from within groovy

Tags:

java

groovy

I have a simple java class:

package test;
class Hello {
  public static void main(String[] args) {
    System.out.println("Hi");
  }
}

on which I do a

javac Hello.java

Problem: Now I would like to access this class from a groovy script (access.groovy) ...

import test.*
Hello.main(null)

but

groovy -cp . access.groovy

will result in a MissingPropertyException . What am I doing wrong?

like image 433
rdmueller Avatar asked Sep 27 '11 10:09

rdmueller


People also ask

Can I use Java code in Groovy?

Groovy scripts can use any Java classes. They can be compiled to Java bytecode (in . class files) that can be invoked from normal Java classes. The Groovy compiler, groovyc, compiles both Groovy scripts and Java source files, however some Java syntax (such as nested classes) is not supported yet.

Can a Groovy class extend a Java class?

Yes, you may intermix Java and Groovy sources in a project and have source dependencies in either direction, including "extends" and "implements".

How do you define a class on Groovy?

A Groovy class is a collection of data and the methods that operate on that data. Together, the data and methods of a class are used to represent some real world object from the problem domain. A class in Groovy declares the state (data) and the behavior of objects defined by that class.


1 Answers

Your class Hello needs to be declared as public to be accessible from other packages. As a dynamic language, Groovy can't identify such errors and ends up looking for a variable named Hello.

It's generally a bad idea to use wildcard imports; in this case, using import test.Hello; would have given you a better error message.

like image 137
Michael Borgwardt Avatar answered Oct 07 '22 20:10

Michael Borgwardt