Script/Groovy

04. Basic Grammer

삽질의 달인 2020. 1. 21. 08:57
이번장에서는 기본적인 Groovy 문법에 대해 알아보자.
 
 
 
Import
 
 
자바의 Import 와 다르지 않다.
 
특정 클래스만 지정할 수 있고 패키지 전체를 포함하고자 하면 * 를 이용할 수 있다.
 
import groovy.xml.MarkupBuilder
 
def xml = new MarkupBuilder()
 
 
Keywords
 
 
Groovy 에서 사용하는 모든 키워드를 확인할 수 있다.
 
키워드는 변수, 함수명 등으로 사용할 수 없다.
 
as
assert
break
case
catch
class
const
continue
def
default
do
else
enum
extends
false
finally
for
goto
if
implements
import
in
instanceof
interface
new
null
package
return
super
switch
this
throw
throws
trait
true
try
while
 
 
 
 
 
Comments
 
Comment 는 거의 Java 와 동일하고 Documentation 부분만 좀 다른데 훨씬 간단하다.
 
//single line comment
def message = "Hello"
 
/*
Multiline comment
*/
 
 
/**
* Documentation Comment
*/
class Person {
 
}
 
 
Assertions
 
groovy 에서는 특정 패키지를 포함하지 않아도 assert 을 제공하여 사용자가 쉽게 결과를 테스트 할 수 있게 해준다.
 
좋은 점은 output 에서 수행된 계산과 false 로 떨어진 부분을 쉽게 확인할 수 있는 점이다.
 
assert 1 == 2
 
Assertion failed:
 
Caught: Assertion failed:
assert 1 == 2
         |
         false
 
assert 1 == (3+10) * 100/5*20
 
Caught: Assertion failed:
 
assert 1 == (3+10) * 100/5*20
                  |       |        |  |
                  | 13   1300  |  5200
                  false          260
 
def x = [1,2,3,4,5]
assert (x << 6) == [6,7,8,9,10]
 
assert (x << 6) == [6,7,8,9,10]
         |    |       |
         |    |       false
         |    [1, 2, 3, 4, 5, 6]
         [1, 2, 3, 4, 5, 6]
 
 
 
Numbers
 
JAVA 에서 숫자는 int 와 Integer 가 있다.
 
하지만 Groovy 에서는 모든 것이 객체로 단순 상수도 Integer 클래스가 랩핑한다.
 
println 1.getClass().getName()
java.lang.Integer
 
 
Annotations
 
 
@ToString
@EqualsAndHashCode
...
 
등의 편리한 Annotations 를 제공하는데 이와 관련해서는 따로 정리할 예정이다.
 
 
 
Grapes
 
 
메이븐 레포지토리에서 필요한 디펜던씨 JAR 파일을 얻는 경우 사용된다.
 
 
를 Groovy 에서 사용하고자 하는 경우 아래와 같이 입력하면 된다.
 
@Grapes(
@Grab(group = 'org.apache.commons', module = 'commons-lang3',version='3.4')
)
 
String name = "Daniel"
def wordUtils = new WordUtils()
println wordUtils.initials(name)