JDK5에 등장한 Generic은 type parameter라는 개념을 도입하면서 자바 프로그래밍을 손쉽게 해줄 수 있는 멋진 언어기능으로 주목받아왔다. Generic을 이용해서 프로그래밍을 해보면 얼마나 편리하게 베이스클래스등을 만들 수 있는지 감탄하게 된다. 하지만 Generic을 좀 더 깊이 살펴보면 그다지 만만한 기술이 아닌 것을 알 수 있다. 자바 언어를 복잡하게 만든 대표적인 기술이라는게 Generic의 비판자들의 공통적인 주장이다. wildcard나 extend의 사용과 generic superclass, generic iterface등을 결합해서 쓸 때 주의 하지 않으면 매우 난해한 코드구조를 만들어 낼 수 있다.

OSAF개발을 할 때 Generic을 적용해서 제일 해피했던 것은 Spring의 HibernateDaoSupport를 Generic을 이용해서 generic DAO구조로 만든 것과 SpringMVC의 컨트롤러에 generic을 적용해 command object등의 불필요한 casting을 사용하지 않도록 만든 것이다.

하지만 문제는 Generic Enumeration을 만들때이다. singleton을 쓸까하다가 편하게 static을 쓰기로 했다. 문제는 static field, method에는 generic을 사용할 수 없다는 사실! 물론 generic method는 static에서 사용가능하지만 generic class의 type parameter를 static method에 적용하는 것은 불가능하다. 이유를 찾아보니 Java generic은 C++의 template과는 달리 컴파일시에 적용되는 것이 아니고 dynamic하게 인스턴스가 만들어질 때 적용된다는 것이다. 잘 이해가 안됐지만 그런가하고 포기하고 넘어갔다.

그러다가 최근에 Generic의 파라메터 정보를 읽어오면 편리하겠다 싶어서 reflection을 이용해서 파라메터 타입을 가져오려고 시도를 해봤으나 불가능했다. 왜 그럴까 생각을 해보다가 좀 더 Generic을 공부해 볼 필요를 느꼈다.

List<String> a;

이런 경우 프로그램 내에서 type parameter값이 무엇인지(String) 알아낼 방법이 없다는 것이다.

이유는 Erasure라는 것 때문이다. Java Generic은 JVM레벨의 호환성을 위해서 컴파일시에 Generic정보(<T>,<V>…)를 삭제해버린다. Generic정보가 없는 Raw Type(List)만 남는다는 것이다. -_-; 따라서 컴파일된 byte code내에는 저 <String>부분은 남아있지 않은 것이고 결국 reflection을 이용해서 그 것을 알아낼 방법이 없다. Generic은 단지 compile시에 타입체킹을 통해서 런타임시의 타입캐스팅을 보장해주는 방식으로 구현되어있다는 것이다.

이에 대해서 논쟁이 많이 있다.

참고해볼만한 것으로

오래됐지만 Generic과 Erasure에 대해서 잘 설명한 글.

Wikipedia의 설명도 읽어볼만 하다

자바의 Generic의 구현방법에 대한 비판 또한 적지 않다.

이러한 백그라운드에서 일어나는 자바의 Generic구현기능 덕분에 사실 여러가지 복잡한 문제가 발생할 수 있다. 그래서 Generic은 점점 더 복잡해진다.

한가지 흥미로운 것은 모든 Generic type정보가 삭제되지 않는다는 사실! Generic의 static한 정보는 컴파일 후에도 남고 이를 런타임시에 확인해서 사용할 방법이 있다. 다만 instance를 만들거나 변수선언에 사용한 정보는 삭제된다.
Rod Harrop은 이에 관해서 아주 좋은 글을 interface21팀 블로그에 올렸다.

한번 읽어서 완벽히 이해하고 적용하기가 쉬운 글은 아니지만 시간을 내서 꼼꼼히 분석해볼 가치가 있는 글이다.

Generic은 마스터하기가 쉬운 기술은 아니지만 적잘하게 사용했을 때 많은 장점이 있기 때문에 자바 개발자라면 반드시 도전해봐야 할 것이다.

Related posts:

  1. Generic DAO Pattern with JDK5.0
  2. Spring에 관한 흥미로운 글 몇가지
  3. Java In Action – New TSS Conference
  4. TheServerSide Java Symposium 2005에 가고 싶다
  5. JSR-330 Dependency Injection for Java 최종 승인
  6. Java Web Framework 비교(Struts, Spring, WebWork, Tapestry, JSF)
  7. 영어, 번역 그리고 발음
  8. 인터페이스 프로그래밍과 IDE 코드네비게이션편의성
  9. EasyMock 2.1 Released
  10. 유쾌한 이슈처리 재촉 메일
  11. S1A 2008 셋째날 – Spring JavaConfig
  12. Spring 3.0 (28) R-669 Update

Facebook comments:

to “Java Generic과 Erasure”

  1. Just over two years buy avodart hair loss online Deposits fell inDecember for the third straight month and bankers expect thetrend to have accelerated in January.

  2. What do you do? phenergan boots pharmacy liquid But apart from a fine header to open the scoring from Arsenal’s No 9 (please, it was nothing), the match was remembered for a spat between Nigel Winterburn and Brian McClair

  3. I didn’t go to university cbd oil capsules and barrett’s esophagus What came through was a group that never panics because it believes it will ultimately win.

  4. Where are you from? kohlls.com “Maybe Moscow is betting on Ukraine\ndisintegrating, but that won’t happen anytime soon.”

  5. I’m from England dbol cycle price “At the margin, (the cuts) may have some small positiveeffect on bank lending and activity and perhaps give the euroanother downward nudge,” said Jonathan Loynes, chief Europeaneconomist at Capital Economics.

  6. About a year generic erectile dysfunction meds gnc Murray’s 1-yard run came a play after rookie Lamarcus Joyner’s interference call in the end zone

  7. I can’t get a signal avodart side effects joint pain journal “Everybody’s got camera phones these days and they want autographs and photos

  8. I’m sorry, she’s leopharmarx.com reviews Bean’s attorney, Kristen Winemiller, said his client is the victim of an extortion ring, and has stressed that “no allegations against Terry Bean should be taken at face value

  9. Yes, I play the guitar powerbar protein plus figur shake erfahrungen Three other tourists – an Australian, a Briton and a German – sustained serious head injuries and were transferred to a hospital in the capital Nairobi after the tour bus crashed through guard rails in Kenya’s Narok County.

  10. I’m sorry, I didn’t catch your name talla baja pills for sale The two CEOs knew each other previously and deepened their relationship last year

  11. Languages celexa price comparison jumperoo “We are absolutely interested in our relations normalising, but it wasn’t us who destroyed them

  12. I’d like to order some foreign currency hair bass tab Sunrise packs in some additional features similar to Apple’s first-party solution, such as integrated mapping to help you get to your events

  13. I used to be recommended this web site by way of my cousin. I am now
    not certain whether or not this post is written through him as nobody else recognize such specific about my difficulty.
    You’re amazing! Thanks!

  14. Can you put it on the scales, please? tadacip cipla review jquery They also said Assaye might be with his girlfriend, whose photo was posted on Twitter but who was not named.

  15. Your cash is being counted zolnite Marine robots come in a variety of strange shape and sizes, and no fewer than four different types are being deployed in this project, part of a new generation of devices designed to make marine research far cheaper and easier than with large crewed vessels.

  16. Could you give me some smaller notes? propecia buy online usa It takes its name as a shortening of climate fiction, much as science fiction is often shortened to “sci-fi”.

  17. I sing in a choir erectile dysfunction drugs uk psychological Connor joined NBC News from the New York Daily News, where she was a senior writer covering a broad range of news and supervising the health and immigration beats

  18. Where’s the nearest cash machine? viagra from india safe Church, the same place where he took refuge as the young chairman of the Student Nonviolent Coordinating Committee

  19. What line of work are you in? can you take prilosec with valium A Gallup spokesman said, “As has been the case historically, Americans are most likely to feel the news media are ‘too liberal’ (44 percent), rather than ‘too conservative’ [19 percent],though this perceived liberal bias is now on the lower side of the trend

  20. The manager catagonia capital Bob Fulkerson with Progressive Leadership Alliance of Nevada said he feared the deal could open the floodgates for other companies seeking similar tax breaks.

  21. A financial advisor jalyn sanders wiki But in Ireland Hutchison ditched the O2 brand altogether as it brought the operations together.

  22. I’m training to be an engineer flagyl uses uti ubs This contrasted with single, retired men with no qualifications and poor health – they consumed an average of five small glasses of wine per week.

  23. I’m not sure purchase naltrexone In an interview, the 43 year old billionaire said that the efforts of his space transport services company SpaceX to build a commercial satellite business will provide it with the infrastructure and know-how that could make it possible to send spacecraft and even build a human colony on the Red Planet.

  24. I’m unemployed acp special issue Tuesday night’s Boca Raton Bowl 2014 arrives courtesy of ESPN for television viewers around the nation, with a start time of 6 p.m

  25. I want to make a withdrawal viviscal shampoo review It would be unwise, however, to hinder the deployment of these new automotive technologies in an attempt to plan for every hypothetical risk scenario associated with robotic vehicles

  26. Heya i am for the first time here. I found this board and I find It really useful & it helped
    me out a lot. I hope to give something back and help others like you aided me.

  27. Have you read any good books lately? feminil como tomar In a sign of increased volatility, the CBOE Volatility Index .VIX, or VIX, the market’s favored gauge of Wall Street anxiety, touched a high of 22.06 on Friday, its highest intraday level since December 2012, as more investors paid up for protection against further declines

  28. I’ve only just arrived dexedrine 5mg ir She added that Cynthia McLelland was not on that list but that her husband later told her he considered McLelland “collateral damage.”

  29. When do you want me to start? ehealthforum.com This makes it possible for users to watch a wide range of cheap movie rentals and prime content.

  30. Until August peter thomas power k eye rescue Euro zone manufacturing activity expanded at a slightlyslower pace than first thought last month as further discountsat the factory gate failed to drive up new orders, a businesssurvey showed on Monday.

  31. History consevel tablet usage A source confirmed the initial report of Thursday night’s meeting and told the Daily News just after 9:30 a.m

  32. Can you hear me OK? disulfiram reaction to alcohol This can raise temperatures in urban areas by as much as 5.4 degrees Fahrenheit over surrounding undeveloped areas.

  33. Thanks for calling buy non prescription cialis But the poll shows no difference by income in comprehending the Fed’s interest rate policy.

  34. What line of work are you in? does phenergan make you sleepy If there is a caution it comes in the way Romney has chosen to modify his image since the last election

  35. What’s Taking place i’m new to this, I stumbled upon this
    I’ve found It absolutely useful and it has aided me out loads.
    I hope to give a contribution & aid different customers like its aided me.
    Great job.

Leave a Reply



You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© 2017 Toby's Epril Suffusion theme by Sayontan Sinha