본문 바로가기
카테고리 없음

자바 리플렉션 예시 코드 (java reflection example)

by 문자메일 2022. 12. 18.

 

리플랙션 타겟 Class

package org.example.reflection;

public class Book {

    public static String A = "A";

    private String B = "B";

    public Book(){

    }

    public Book(String b){
        B = b;
    }

    private void c(){
        System.out.println("C");
    }

    public int sum(int left, int right){
        return left + right;
    }

}

 

 

 

리플랙션으로 읽는 코드 예시

package org.example.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BookMain {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        Class<?> bookClass = Class.forName("org.example.reflection.Book");
        Constructor<?> constructor = bookClass.getConstructor(String.class);
        Book book = (Book) constructor.newInstance("myBook");
        System.out.println(book);

        Field a = Book.class.getDeclaredField("A");
        System.out.println(a.get(null));

        Field b = Book.class.getDeclaredField("B");
        b.setAccessible(true);
        System.out.println(b.get(book));

        b.set(book, "BBBBB");
        System.out.println(b.get(book));

        Method c = Book.class.getDeclaredMethod("c");
        c.setAccessible(true);
        c.invoke(book);

        Method d = Book.class.getDeclaredMethod("sum", int.class, int.class);
        int invoke = (int) d.invoke(book, 1, 2);
        System.out.println(invoke);
    }
}

댓글