개발/Java

Annotation 생성

Ricetherapy 2021. 2. 9. 10:47

어노테이션을 생성해서 해당 어노테이션의 값으로 특정 변수, 클래스에 지정해주어 어노테이션을 가진 오브젝트에 대해 어떠한 처리를 추가할 수 있다.

 

어노테이션 생성 방법

@Retention(RUNTIME)
@Target(FIELD)
public @interface BVparam {
	boolean hash() default false;
}
  • @Retention - 어노테이션의 범위. 어떤 시점까지 어노테이션이 영향을 미치는지 결정.
  • @Documented - 문서에도 어노테이션의 정보가 표현됩니다.
  • @Target - 어노테이션이 적용할 위치를 결정합니다.
  • @Inherited - 이 어노테이션을 선언하면 자식클래스가 어노테이션을 상속 받을 수 있습니다.
  • @Repeatable - 반복적으로 어노테이션을 선언할 수 있게 합니다.
@Retention - Specifies how the marked annotation is stored—Whether in code only, compiled into the class, or available at runtime through reflection.
@Documented - Marks another annotation for inclusion in the documentation.
@Target - Marks another annotation to restrict what kind of Java elements the annotation may be applied to.
@Inherited - Marks another annotation to be inherited to subclasses of annotated class (by default annotations are not inherited to subclasses).
@Repeatable - Specifies that the annotation can be applied more than once to the same declaration, since Java 8.

표 출처 - https://en.wikipedia.org/wiki/Java_annotation

 

Java annotation - Wikipedia

In the Java computer programming language, an annotation is a form of syntactic metadata that can be added to Java source code.[1] Classes, methods, variables, parameters and Java packages may be annotated. Like Javadoc tags, Java annotations can be read f

en.wikipedia.org

 

@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME) // 컴파일 이후에도 JVM에 의해 참조
//@Retention(RetentionPolicy.CLASS) // 컴파일러가 클래스 참조 시 까지 유효
//@Retention(RetentionPolicy.SOURCE) // 어노테이션 정보는 컴파일 전까지 유효
@Target({
        ElementType.PACKAGE, // 패키지 선언시
        ElementType.TYPE, // 타입 선언시
        ElementType.CONSTRUCTOR, // 생성자 선언시
        ElementType.FIELD, // 멤버 변수 선언시
        ElementType.METHOD, // 메소드 선언시
        ElementType.ANNOTATION_TYPE, // 어노테이션 타입 선언시
        ElementType.LOCAL_VARIABLE, // 지역 변수 선언시
        ElementType.PARAMETER, // 매개 변수 선언시
        ElementType.TYPE_PARAMETER, // 매개 변수 타입 선언시
        ElementType.TYPE_USE // 타입 사용시
})

 

사용 방법

사용할 오브젝트의 앞에 어노테이션을 붙여서 사용한다

@BVparam		String email;
@BVparam(hash = true)	String passwd;

 

오브젝트 처리 시 어노테이션의 유무와 속성값으로 추가적인 처리를 할 수 있다.

Field f = _voClazz.getDeclaredField(jsonEntry.getKey());
			BVparam param = f.getAnnotation(BVparam.class);
			if (f != null && param != null) {
        		boolean accessible = f.isAccessible();
        		f.setAccessible(true);
        		if (f.getType().isAssignableFrom(String.class)) {
        			String value = jsonEntry.getValue().toString();
        			if (param.hash()) {
        				value = CryptoUtil.getSHA256(value.getBytes());
        			}
        		}
        	}