프로그래머호이잇

[Java/자바 기초] annotation 활용 본문

java

[Java/자바 기초] annotation 활용

호이잇! 2017. 1. 3. 17:04

이번에는 annotation을 이용하여 annotation이 붙어있는 클래스의 annotation이 붙은 메소드를 실행해 보겠습니다.


먼저 annotation 2개를 만들어 줍니다.









위와 같이 2개의 어노 테이션을 만들어줍니다 그후 어노테이션을 적용할 클래스를 만들어 줍니다.



이러면 모든 준비가 끝났습니다. 


자 인제 위에 말했다 시피 모든 클래스 들중에 어노테이션 붙은 클래스를 찾아 저기 보이는 annotationPrint 라는 메소드를 실행 시켜 봅시다




이게 바로 실행 코드입니다. 


이코드를 실행하시면 아까 만든 "실행이 되었습니다" 라는 문구가 보이실겁니다.


코드에 대한 설명을 하자면 


저 패키지 네임은 class 파일들이 위치한 패키지명을 입력하여 주시면됩니다.


디렉토리에서 .class 파일을 찾아 Class.forName 을 이용하여 Class 객체를 로드 합니다. 


그후 Class 객체의 어노테이션 여부를 검사하고 Class에 정의된 모든 메소드를 불러와서 그 메소드들의 어노테이션 여부를 검사하여 위에 빨간 박스로 된 invoke 함수로 실행을 하여 주는 코드 입니다. 실행을할때에는 실행이 되는 클래스를 생성하여 Argument로 전달하여 주어야합니다. 


그래서 con.newInstance() 라는 코드가 안에 들어가있는 것 입니다.


코드가 너무기니 아래에 붙여 드리겠습니다


package main.java.com.main;


import java.io.File;

import java.lang.annotation.Annotation;

import java.lang.reflect.Constructor;

import java.lang.reflect.Method;

import java.net.URL;


import main.java.com.annotation.Controller;

import main.java.com.annotation.Mapping;


public class Main2 {

public static void main(String[] args) {

String packageName = "main.java.com.test";

String packageNameSlash = "./" + packageName.replace(".", "/");

URL directoryURL = Thread.currentThread().getContextClassLoader()

.getResource(packageNameSlash);

if (directoryURL == null) {

System.err.println("Could not retrive URL resource : "

+ packageNameSlash);

}


String directoryString = directoryURL.getFile();

if (directoryString == null) {

System.err.println("Could not find directory for URL resource : "

+ packageNameSlash);

}


File directory = new File(directoryString);

if (directory.exists()) {

String[] files = directory.list();

for (String fileName : files) {

if (fileName.endsWith(".class")) {

fileName = fileName.replace(".class", "");

try {

Class temp = Class.forName(packageName +'.' + fileName);

Annotation[] annotations = temp.getAnnotations();

Constructor con = temp.getConstructor();

for (Annotation annotation : annotations) {

if (annotation instanceof Controller) {

Controller myAnnotation = (Controller) annotation;

for (Method method : temp.getDeclaredMethods()) {

if (method.isAnnotationPresent(Mapping.class)) {

method.invoke(con.newInstance());

}


}

}

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

}

}