groovy와 java의 차이점

2012. 8. 28. 19:47 from JAVA

http://groovy.codehaus.org/Differences+from+Java

 

Differences from Java

Groovy tries to be as natural as possible for Java developers. We've tried to follow the principle of least surprise when designing Groovy, particularly for developers learning Groovy who've come from a Java background.

그루비는 되도록 자바 개발자에게는 자연스럽게 와닿을 수 있도록 노력하였다. 그루비를 설계할 때, 자바 배경지식을 가진 사람이 그루비를 학습한다고 하면 최소한의 차이점만을 느끼도록 한다는 원칙으로 만들었다.

Here we list all the major differences between Java and Groovy.

다음은 자바와 그루비의 주요 차이점이다.

 

Default imports

All these packages and classes are imported by default, i.e. you do not have to use an explicit import statement to use them:

아래 패키지와 클래스는 기본적으로 import되는 것들이다. 따라서, 명시적으로 import문으로 아래 패키지를 적지 않아도 포함되어 있다.

  • java.io.*
  • java.lang.*
  • java.math.BigDecimal
  • java.math.BigInteger
  • java.net.*
  • java.util.*
  • groovy.lang.*
  • groovy.util.*

Common gotchas

일반적인 차이점 

Here we list the common things you might trip over if you're a Java developer starting to use Groovy.

다음은 그루비를 시작하는 자바 개발자가 흔히 겪는 일들이다.

  • == means equals on all types. In Java there's a wierd part of the syntax where == means equality for primitive types and == means identity for objects. Since we're using autoboxing this would be very confusing for Java developers (since x == 5 would be mostly false if x was 5 (smile) . So for simplicity == means equals() in Groovy. If you really need the identity, you can use the method "is" like foo.is(bar). This does not work on null, but you can still use == here: foo==null.
  • ==는 모든 형식에서 동등함을 의미한다. 자바에서는 이상하게도 ==가 기본형(primitive type)의 동등함은 물론 객체가 일치함을 뜻하기도 한다. 그루비에서는 오토박싱(autoboxing)을 사용하므로 자바 개발자에게는 혼란스러울 수도 있다. (x==5는 x가 5라면 대부분 false일 것이다. 그래서 그루비에서는 ==는 equals()를 뜻한다.) 객체 일치가 필요하다면 foo.is(bar)와 같이 "is"메소드를 사용하면 된다. 이방식은 null에서는 동작하지 않지만 foo==null과 같이 사용할 수 있다.
  • in is a keyword. So don't use it as a variable name.
  • in은 키워드다. 따라서 변수명으로 사용할 수 없다.
  • When declaring array you can't write
  • 배열은 아래와 같이 선언하면 안된다.
  • int[] a = {1,2,3};

    you need to write 대신 아래와 같이 쓴다.

  • int[] a = [1,2,3]
  • If you are used to writing a for loop that looks like 아래와 같은 for 루프를 주로 썻다고 해보자
    for (int i=0; i < len; i++) {...}

    in groovy you can use that too, but you can use only one count variable. Alternatives to this are

  • for (i in 0..len-1) {...}

  • or

    for (i in 0..<len) {...}

    or

    len.times {...}

Things to be aware of

  • Semicolons are optional. Use them if you like (though you must use them to put several statements on one line).
  • The return keyword is optional.
  • You can use the this keyword inside static methods (which refers to this class).
  • Methods and classes are public by default.
  • Protected in Groovy has the same meaning as protected in Java, i.e. you can have friends in the same package and derived classes can also see protected members.
  • Inner classes are not supported at the moment. In most cases you can use closures instead.
  • The throws clause in a method signature is not checked by the Groovy compiler, because there is no difference between checked and unchecked exceptions.
  • You will not get compile errors like you would in Java for using undefined members or passing arguments of the wrong type. See Runtime vs Compile time, Static vs Dynamic.

Uncommon Gotchas

Java programmers are used to semicolons terminating statements and not having closures. Also there are instance initializers in class definitions. So you might see something like:

class Trial {
  private final Thing thing = new Thing ( ) ;
  { thing.doSomething ( ) ; }
}

Many Groovy programmers eschew the use of semicolons as distracting and redundant (though others use them all the time - it's a matter of coding style). A situation that leads to difficulties is writing the above in Groovy as:

class Trial {
  private final thing = new Thing ( )
  { thing.doSomething ( ) }
}

This will throw a MissingMethodException!

The issue here is that in this situation the newline is not a statement terminator so the following block is treated as a closure, passed as an argument to the Thing constructor. Bizarre to many, but true. If you want to use instance initializers in this sort of way, it is effectively mandatory to have a semicolon:

class Trial {
  private final thing = new Thing ( ) ;
  { thing.doSomething ( ) }
}

This way the block following the initialized definition is clearly an instance initializer.

Another document lists some pitfalls you should be aware of and give some advice on best practices to avoid those pitfalls. 

New features added to Groovy not available in Java

  • Closures
  • native syntax for lists and maps
  • GroovyMarkup and GPath support
  • native support for regular expressions
  • polymorphic iteration and powerful switch statement
  • dynamic and static typing is supported - so you can omit the type declarations on methods, fields and variables
  • you can embed expressions inside strings
  • lots of new helper methods added to the JDK
  • simpler syntax for writing beans for both properties and adding event listeners
  • safe navigation using the ?. operator, e.g. "variable?.field" and "variable?.method()" - no more nested ifs to check for null clogging up your code

'JAVA' 카테고리의 다른 글

[jstl] 모델2JSP책 9장에 실리지 않은 내용  (0) 2012.10.25
eclipse - SVN 에러 - RA layer request failed  (0) 2012.10.24
OOM 발생시 heap Dump 옵션  (0) 2012.08.14
JSTL 숫자 포맷  (0) 2012.05.18
이클립스 단축키  (0) 2012.04.06
Posted by 에시드 :