Groovy language is most proud of the characteristics of the DSL, the definition of DSL and classification, advantages, etc., it is not to be elaborated in this article, you can access the Internet, there is a large number of this convenient introduction. The groovy language is a great way to design your internal DSL, and in this context, my Groovy Discovery series has a number of topics that talk about some aspects of creating an internal DSL using the groovy language. This article explores a very small and very humble aspect of the groovy language DSL: A DSL about the name of the method.
When it comes to the DSL of method names, we already have a very wide range of applications in the groovy language. For example, when we first learn the groovy language, we write a "HelloWorld" program to start our first groovy language program, which has the following code:
public class HelloWorld{
/**
* @param args
*/
public static void main(def args){
// TODO Auto-generated method stub
println 'Hello,World!'
}
}
The results of its operation do not let me say more. We are interested in the "println" approach, and we all know that in the Java language the corresponding method is "System.out.println". The long method name, "System.out.println", is written as "println", which is an application of the DSL for methods in the groovy language. Such benefits are mainly two aspects: the first is the rapid increase in coding, input "println" of course, also input "System.out.println" convenient a lot; the second is the enhancement of readability, which is the pursuit of DSL, "println" is more readable than " System.out.println "Strong.
So how do we implement a DSL like "println" in the actual coding process?
The DSL for the method name has three implementations in the groovy language, two of which are static introduction and use of the "as" keyword, respectively. Let's use one example to illustrate it.
For example, we want to get the current time of the system, the Java language Way is as follows:
System.out.println(System.currentTimeMillis())
With the static introduction, our code in the groovy language will be like this:
import static System.currentTimeMillis
/**
* @author Administrator
*
*/
public class Testor2{
/**
* @param args
*/
public static void main(def args){
// TODO Auto-generated method stub
println currentTimeMillis()
}
}
Of course, we can go further, and the code using the "as" keyword would be like this:
import static System.currentTimeMillis as now
/**
* @author Administrator
*
*/
public class Testor2{
/**
* @param args
*/
public static void main(def args){
// TODO Auto-generated method stub
println now()
}
}