code manipulation: relfection(annotation)

This commit is contained in:
haerong22
2021-02-19 20:38:47 +09:00
parent b30a888de3
commit afbe183231
5 changed files with 48 additions and 2 deletions

View File

@@ -0,0 +1,30 @@
package org.example;
import java.util.Arrays;
public class AnnotationApp {
public static void main(String[] args) {
// 원하는 필드의 애노테이션의 값 가져오기
Arrays.stream(Book.class.getDeclaredFields()).forEach(f -> {
Arrays.stream(f.getAnnotations()).forEach(a -> {
if (a instanceof MyAnnotation) {
MyAnnotation myAnnotation = (MyAnnotation) a;
System.out.println(myAnnotation.name());
System.out.println(myAnnotation.number());
}
});
});
// // 필드에 사용한 애노테이션 가져오기
// Arrays.stream(Book.class.getDeclaredFields()).forEach(f -> {
// Arrays.stream(f.getAnnotations()).forEach(System.out::println);
// });
// // 클래스에 있는 애노테이션 가져오기
// Arrays.stream(Book.class.getAnnotations()).forEach(System.out::println);
}
}

View File

@@ -1,7 +1,10 @@
package org.example;
@MyAnnotation(name = "lee", number = 20)
public class Book {
@MyAnnotation
private static String B = "BOOK";
private static final String C = "BOOK";

View File

@@ -4,7 +4,7 @@ import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
public class App {
public class ClassApiApp {
public static void main( String[] args ) throws ClassNotFoundException {

View File

@@ -0,0 +1,13 @@
package org.example;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD})
@Inherited
public @interface MyAnnotation {
String name() default "kim"; // 기본값을 주지 않으면 애노테이션 사용시 반드시 값을 넣어야 한다.
int number() default 100;
}

View File

@@ -7,7 +7,7 @@ import org.junit.Test;
/**
* Unit test for simple App.
*/
public class AppTest
public class ClassApiAppTest
{
/**
* Rigorous Test :-)