code manipulation: relfection(annotation)
This commit is contained in:
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
package org.example;
|
package org.example;
|
||||||
|
|
||||||
|
|
||||||
|
@MyAnnotation(name = "lee", number = 20)
|
||||||
public class Book {
|
public class Book {
|
||||||
|
|
||||||
|
@MyAnnotation
|
||||||
private static String B = "BOOK";
|
private static String B = "BOOK";
|
||||||
|
|
||||||
private static final String C = "BOOK";
|
private static final String C = "BOOK";
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import java.lang.reflect.Field;
|
|||||||
import java.lang.reflect.Modifier;
|
import java.lang.reflect.Modifier;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
|
|
||||||
public class App {
|
public class ClassApiApp {
|
||||||
public static void main( String[] args ) throws ClassNotFoundException {
|
public static void main( String[] args ) throws ClassNotFoundException {
|
||||||
|
|
||||||
|
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -7,7 +7,7 @@ import org.junit.Test;
|
|||||||
/**
|
/**
|
||||||
* Unit test for simple App.
|
* Unit test for simple App.
|
||||||
*/
|
*/
|
||||||
public class AppTest
|
public class ClassApiAppTest
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Rigorous Test :-)
|
* Rigorous Test :-)
|
||||||
Reference in New Issue
Block a user