DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

Write Groovy Codes instead of Java


Writing Java codes in terminal is a pain for tons of boilerplate. But sometimes you have to. So we can write groovy instead.

Origin Java codes (Convert.java):

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 
import org.apache.commons.lang3.StringEscapeUtils; 
public class Convert { 
    public static void main(String[] args) throws IOException { 
        BufferedReader reader = new BufferedReader(new FileReader("target")); 
        String line = reader.readLine(); 
        System.out.println("file content: "+line); 
        String out = StringEscapeUtils.unescapeJava(line); 
        System.out.println("from string to char: " + out); 
        String out2 = StringEscapeUtils.escapeJava(out); 
        System.out.println("from char to string : " + out2); 
    } 
}

$ javac -cp commons-lang3-3.2.1.jar:. Convert.java

$ java -cp commons-lang3-3.2.1.jar:. Convert

Corresponding Groovy codes (convert.groovy):

import org.apache.commons.lang3.StringEscapeUtils 
def reader = new BufferedReader(new FileReader("target")) 
def line = reader.readLine() 
println "file content: $line" 
def out = StringEscapeUtils.unescapeJava(line) 
println "from string to char: $out" 
def out2 = StringEscapeUtils.escapeJava(out) 
println "from char to string: $out2"

Run it: groovy -cp commons-lang3-3.2.1.jar convert.groovy

Key points to writing groovy codes:

  1. Dynamic type but with "def" (see "http://stackoverflow.com/questions/184002/groovy-whats-the-purpose-of-def-in-def-x-0" for its reason);

  2. No need to import Java built-in library;

  3. No need to take care of the exceptions;

  4. semi-colon at the end of line is optional;

  5. Use "println" instead of "System.out.println...";

Ref:

http://stackoverflow.com/questions/764416/why-would-one-use-groovy-over-java



Published

Jan 9, 2014

Last Updated

Jan 9, 2014

Category

Tech

Tags

  • groovy 13
  • Java 106

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor