달력

5

« 2024/5 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
2009. 7. 24. 16:06

AspectJ ITD를 이용한 ActiveRecord 구현 Java2009. 7. 24. 16:06

aspectj의 ITD(Inter-Type Declaration)은 roo로 인해 보다 유명해 진 기술로써 클래스에 존재하지 않는 메소드를 추가하거나 존재하지 않았던 관계(extends, implements 등)을 추가하여 클래스의 타입을 변경할 수 있는 기술이다.

이 글에서는 find 메소드를 POJO에 추가하는 것을 aspectj ITD를 이용해서 구현해 본다.  또 ITD로 find 메소드 정의시 generic을 사용해서 타입 캐스팅이 불필요하도록 한다.

1. Test

public class ArticleTest {

@Test

public void find() {

Article key = new Article();

Article a = (Article) new Article().find(key);

assertThat(a, is(key));


ArticleContent key2 = new ArticleContent();

ArticleContent a2 = (ArticleContent) new ArticleContent().find(key2);

assertThat(a2, is(key2));

}

}


위 테스트는 find 메소드를 호출하여 그 값이 key와 동일한지 비교하는 테스트이다.

Article, ArticleContent 클래스에는 find 메소드가 존재하지 않는다.


2. Aspect

privileged aspect ActiveRecordITD {

public interface ActiveRecord {};

declare parents : Article implements ActiveRecord;

declare parents : ArticleContent implements ActiveRecord;

@SuppressWarnings("unused")

private void ActiveRecord.log(String methodName) {

System.out.println(this.getClass().getSimpleName()+"#" + methodName +" called !!!");

}

public <T> T ActiveRecord.find(T key) {

log("find");

return key;

}

}

 

위 aspect에서 특이한 부분을 살펴보도록 하자.

privileged: weaving할 클래스의 private까지도 access 가능하도록 한다.

declare parents: 해당 클래스가 특정 인터페이스를 구현하도록 한다.

public <T> T ActiveRecord.find(T key): ActiveRecord를 구현하는 클래스들에 해당 메소드를 제공한다.


지금까지 간략하게 generic 메소드를 제공하는 ITD를 구현하는 방법을 간략하게 알아보았다. 실제의 경우라면 find 메소드가 보다 복잡해야겠지만서도...


:
Posted by codetemplate