memostack
article thumbnail
Published 2020. 8. 20. 09:42
Groovy! JAVA와의 차이점 Language/Groovy
블로그를 이전하였습니다. 2023년 11월부터 https://bluemiv.tistory.com/에서 블로그를 운영하려고 합니다. 앞으로 해당 블로그의 댓글은 읽지 못할 수 도 있으니 양해바랍니다.
반응형

Default Import

아래 패키지는 기본으로 import 되어 있기 때문에 바로 사용 가능하다.

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

 

Multi-Methods

  • 그루비는 런타임시의 인수 유형에 따라 적절한 메소드를 선택하여 실행 함.
  • 이렇게 호출하는 방식을 디스패치(Dispatch) 또는 다중메소드(Multi-Methods)라고 함.
int method(String arg) {
    return 1;
}

int method(Object arg) {
    return 2;
}

Object o = "Object";
int result = method(o); // Groovy는 런타임시에 인수에 따라 적절한 메소드를 호출 함

println(result)  // 1
  • 위에서는 그루비가 Object o를 런타임시에 문자열로 보기 때문에 method 호출시 int method(String arg)로 호출한다.
  • Java에서는 2라는 값을 기대하겠지만, Groovy에서는 1을 반환한다.

 

Array initialize

// int[] array = {1, 2, 3}; // JAVA 문법
int[] array = [1, 2, 3]; // Groovy 문법
println(array)

// groovy 3.0+ 부터는 아래와 같이 사용 가능
int[] array2 = new int[] {4, 5, 6};
def array3 = new int[] {7, 8, 9}
println(array2)
println(array3)

 

Package Scope Visibility

package-private으로 필드를 생성하고 싶을때는 @PackageScope 를 사용한다.

import groovy.transform.PackageScope

class PersonGroovy {
    @PackageScope String name
}

class PersonJava {
    String name
}

 

ARM Blocks

JAVA 7에서 소개된 ARM (Automatic Resource Management) blocks.

  • 리소스를 직접 close() 할 필요 없이 자동으로 해제시켜줌
// JAVA
Path file = Paths.get("/path/to/file");
Charset charset = Charset.forName("UTF-8");
try (BufferedReader reader = Files.newBufferedReader(file, charset)) {
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }

} catch (IOException e) {
    e.printStackTrace();
}

// Groovy 3+
new File('/path/to/file').eachLine('UTF-8') {
   println it
}

// Groovy - 만약 JAVA의 클로저와 비슷하게 사용하고 싶다면 아래와 같이 한다.
new File('/path/to/file').withReader('UTF-8') { reader ->
   reader.eachLine {
       println it
   }
}

 

 

Inner Classes

Static Inner Class

class A {
    static class B {}
}

new A.B()

Anonymous Inner Class

import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit

CountDownLatch called = new CountDownLatch(1)

Timer timer = new Timer()
timer.schedule(new TimerTask() {
    void run() {
        called.countDown()
    }
}, 0)

assert called.await(10, TimeUnit.SECONDS)

 

Reference

http://groovy-lang.org/differences.html

 

The Apache Groovy programming language - Differences with Java

In Java == means equality of primitive types or identity for objects. In Groovy == means equality in all cases. It translates to a.compareTo(b) == 0, when evaluating equality for Comparable objects, and a.equals(b) otherwise. To check for identity (referen

groovy-lang.org

 

반응형

'Language > Groovy' 카테고리의 다른 글

Groovy 다운로드 및 사용 환경 구축 (Version 3.0.5)  (0) 2020.08.20
블로그를 이전하였습니다. 2023년 11월부터 https://bluemiv.tistory.com/에서 블로그를 운영하려고 합니다. 앞으로 해당 블로그의 댓글은 읽지 못할 수 도 있으니 양해바랍니다.
profile

memostack

@bluemiv_mm

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!