Let's do something silly, but to see how the things are interacting between each other. For example, let's read our "/etc/passwd" into a list and display a first element of it from a plain Java, omitting an empty lines and/or commented ones. :-) Here how it is done in NetBeans IDE:
- Make sure Groovy support is in your NetBeans 6+. Usually it is there out of the box, but maybe some plugins must be installed. Check it by Plugin Manager, navigating to "Menu→Tools→Plugins" and see maybe you need some tweaks in Preferences for Groovy specifically.
- Create new Java Application project. Let's call it "JavaAndGroovy".
- In your package, called now "javaandgroovy" create a Groovy Class. Since it is an example, let's call it "Grovample".
package javaandgroovyNow, to use this class in the plain Java, just... use this class! Like this:
class Grovample {
def readfile(filename) {
List data = []
for (line in new File(filename).readLines()) {
line = line.trim()
if (line && !line.startsWith("#")) {
data.add(line)
}
}
return data
}
}
package javaandgroovy;As a result, I am getting the following output:
import java.util.List;
public class Main {
public static void main(String[] args) {
List passwd= (List) new Grovample().readfile("/etc/passwd");
System.out.println("Lines: " + passwd.size());
if (passwd.size() > 0) {
System.out.println("First line: \n" + passwd.get(0));
} else {
System.err.println("Well, you're on Windows. :-P");
}
}
}
Lines: 40Now, let's look how the distribution looks like. Press "Clean and Build" button or simply navigate to your project directory in the terminal and run "ant" command. In a "dist" subdirectory, here is the following tree:
First line:
nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false
.File "groovy-all.jar" has a weight of 2.7Mb. Not so small for very tiny apps, but not so big for bigger ones. You might consider put this lib in your GlassFish somewhere, in order to do not deploy it every time with your WAR/EAR. :-)
./JavaAndGroovy.jar
./lib
./lib/groovy-all.jar
./README.TXT
Keep in mind: Groovy is significantly slower than plain Java. Really slow. Check out it how much slower. Still, it does not means that we can not use Groovy for many-many tasks around and simplify our Java code.
Happy Grooving! :-)
1 comment:
You're right: although Groovy is solwer than plain Java you shouldn't stop using it - in most cases you won't notice the performance penalty.
Post a Comment