검색결과 리스트
글
LANGUAGE/Java & Groovy
2019. 8. 19. 12:52
Groovy (그루비)
try with resource
Java7 부터 생긴 자동자원닫기(?) 기능이 있는데 Groovy에서는 그대로 사용하지 못한다. (지원하지 않는다.)
이를 대체하기 위해서는 몇가지 알아야할 사항이 있다.
Closeable 인터페이스를 구현한 객체라면 다음과 같이 withCloseable
Closure로 같은 효과를 볼 수 있다.
(Groovy 2.4(?) 2.5(?) 부터
사용 가능하다.)
형식
class SomeClass implements Closeable {
def print() {
println "Hello SomeClass !!"
}
@Override
public void close() {
println "SomeClass was Closed."
}
}
new SomeClass().withCloseable {
//Something to do..
}
예제
자바에서는 다음과 같이 사용하지만
Java
byte[] buffer = new byte[2048]; int len; try(FileInputStream fis = new FileInputStream("/path/to/file")){ while ((len = fis.read(buffer)) > 0){ //Somthing to do.. } }catch(IOException e){ e.printStackTrace(); }
그루비에서는 컴파일오류가 발생한다. withCloseable
로 대체 할 수 있지만..
Groovy
byte[] buffer = new byte[2048] int len new A().withCloseable { while ((len = fis.read(buffer)) > 0){ //Somthing to do.. } }
예외처리도 try/catch(IOException)
으로 따로 해야하는 것 같다.
호환이 안되니까 뭔가 좀 그렇다...
참고
- Interface AutoCloseable: http://docs.groovy-lang.org/docs/next/html/groovy-jdk/java/lang/AutoCloseable.html
- GroovyのwithCloseableでtry-with-resourcesを実現する: https://qiita.com/mas0061/items/e965c2a07ea5ebfd6a42
- Spock: Up and Running: Writing Expressive Tests in Java and Groovy: https://books.google.co.kr/books?id=m3_PDgAAQBAJ&pg=PT259&lpg=PT259&dq=groovy+withCloseable+try+catch&source=bl&ots=sqahGdbKsQ&sig=ACfU3U06-yPR1ln5eLZ9rLBZ3Vc3Cv6q5g&hl=ko&sa=X&ved=2ahUKEwj_uY3MgY7kAhV6yosBHV9lCXIQ6AEwBXoECAkQAQ#v=onepage&q=groovy%20withCloseable%20try%20catch&f=false
'LANGUAGE > Java & Groovy ' 카테고리의 다른 글
[Java] abstract class와 interface 차이점 (0) | 2020.03.15 |
---|---|
[Java] public static void main(String[] args) 갖고 놀기 🤹♂️ (2) | 2020.03.14 |
[Java] try-with-resources (가독성 높이기) (0) | 2019.08.19 |
[Java] Logback - EvaluatorFilter를 이용해서 경우에 따라 로그에 색입히기 예제 (0) | 2018.02.01 |
[Java] Logback - logback-test.xml과 개발용 설정 만들기 (0) | 2018.01.31 |