Refletion이란?


투영, 반사라는 사전적 의미

객체를 통해 클래스의 정보를 분석하는 기법을 말한다.


자바에서 동적으로 인스턴스를 생성하기 위해 java.lang.reflet api를 통해 제공하고 있다.

이를 이용하면 동적으로 클래스를 생성할 수 있을 뿐만 아니라, 클래스의 메소드를 실행할 수 있다.


예제코드)


다음과 같은 클래스가 있다고 가정


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class TargetClass {
    
    /*
    * reflection 되어질 객체
    */
 
    public void firstMethod() {
        System.out.println("첫번째 매소드");
    }
    
    public void secondMethod(String name) {
        System.out.println("두번째 메소드");
    }
    
    public void thirdMethod(int n) {
        for(int i=0;i<n;i++) {
            System.out.println("세번째 메소드");
        }
    }
}
cs



클래스의 이름을 입력하여 클래스를 찾고 클래스의 선언된 메소드들 찾기


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.lang.reflect.Method;
 
public class ReflectionExample {
    public static void main(String[] args) {
        
        /*
         * 클래스의 선언된 메서드를 찾는 방법
         */
        
        try {
            Class targetClass = Class.forName("co.kr.javastudy.reflection.TargetClass");
//java.lang.Class의 forName()메소드를 통해 클래스를 찾음
            
Method methods[] = targetClass.getDeclaredMethods();
            //getDeclaredMethods()를 통해 해당 클래스의 메소드들을 찾음
for(int i=0;i<methods.length;i++) {
                System.out.println(methods[i].toString());
            }
        } catch (ClassNotFoundException e) {
            System.out.println("클래스를 찾을 수 없습니다.");
        }
    }
}

cs



클래스의 선언된 메소드들의 이름 출력


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.lang.reflect.Method;
 
public class ReflectionExample2 {
    public static void main(String[] args) {
        
        /*
         * 클래스의 선언된 메서드이름을 출력
         */
        
        try {
            Class targetClass = Class.forName("co.kr.javastudy.reflection.TargetClass"); 
            Method methods[] = targetClass.getDeclaredMethods(); 
          
            for(int i=0;i<methods.length;i++) {
                String findMethod = methods[i].getName(); //method의 이름 추출
                System.out.println(findMethod);
            }
        } catch (ClassNotFoundException e) {
            System.out.println("클래스를 찾을 수 없습니다.");
        }
    }
}
cs



찾은 메소드를 동적으로 호출


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
 
public class ReflectionExample3 {
    public static void main(String[] args) {
        
        /*
         * 이름을 지정해 특정 메소드를 실행시키는 방법
         */
        
        try {
            TargetClass target = new TargetClass(); //해당 클래스의 인스턴스 생성
            Class targetClass = Class.forName("co.kr.javastudy.reflection.TargetClass");
            Method methods[] = targetClass.getDeclaredMethods();
            
            for(int i=0;i<methods.length;i++) {
                String findMethod = methods[i].getName();
                if(findMethod.equals("secondMethod")) {
                    //secondMethod를 찾아서 실행
                    try {
                        methods[i].invoke(target,"리플렉션");
                        //invoke()를 통해 메소드 호출 가능
                        //첫번째 파라미터는 해당 메소드를 가진 인스턴스, 두번쨰 파라미터는 해당 메소드의 파라미터
                    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            System.out.println("클래스를 찾을 수 없습니다.");
        }
    }
}
cs



** 리플렉션을 통해 파라미터, 부모 클래스, 패키지, Modifier, Fields, Annotaion 등 다양한 정보를 알아낼 수 있다.

자세한 것은 java api문서를 참고하면 좋을 것 같다.

'Java' 카테고리의 다른 글

오버로딩 vs 오버라이딩  (0) 2017.05.16
JAVA 특징와 OOP  (0) 2017.05.12
[Collection] 동기화된 컬렉션  (0) 2017.03.10
[람다식]메소드와 생성자 참조  (0) 2017.03.08
[람다식] 클래스 멤버와 로컬변수의 사용  (0) 2017.02.24

깊이 우선 탐색


그래프 G와 시작점 S가 주어졌을 때 S에서 도달 가능한 모든 간선을 찾는 과정


동작원리


탐색 시작 위치의 vertex의 인접한 간선을 통해 다른 vertex로 이동한 후 인접한 간선이 없을 때까지

반복하여 내려간 후 다시 위로 올라가는 과정을 반복해서 탐색하는 것


아래로 깊이 내려가며 탐색하기에 깊이 우선 탐색이라고 불림



코드)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class DfsExample {
    
    /*
     * 인접행렬로 구현된 그래프의 깊이 우선 탐색
     */
    
    static int nV; //총 vertex 수
    static int nE; //총 edge 수
    static int[][] adMatrix; //인접행렬
    static boolean[] visit; //방문여부 체크
    
 
    //재귀호출을 이용한 dfs구현
    
    public static void dfs(int i) {
        visit[i] = true;
        for(int j=0;j<nV;j++) {
            if(adMatrix[j][i]==1 && !visit[j]) {
                System.out.println(i + "에서 " + j + "로 이동");
                dfs(j);
            }
        }    
    }
 
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        nV = scan.nextInt();
        nE = scan.nextInt();
        
        adMatrix = new int[nV][nV];
        visit = new boolean[nV];
        
        for(int i=0;i<nE;i++) {
            int vertex1, vertex2;
            vertex1 = scan.nextInt();
            vertex2 = scan.nextInt();
            adMatrix[vertex2][vertex1] = 1;
        }
        
    
        for(int i=0;i<nV;i++) {
            System.out.print(i + "-" );
            for(int j=0;j<nV;j++) {
                System.out.print(adMatrix[j][i]+ " ");
            }
            System.out.println();
        }
 
        
        dfs(0);
    }
}
cs


동기화된 컬렉션


컬렉션 프레임워크의 대부분의 클래스들은 싱글 스레드 환경에서 사용할 수 있도록 설계되어있음

그렇기에 여러 스레드가 동시에 컬렉션에 접근한다면 의도하지 않게 데이터가 변경될 수 있는

불안정한 상태가 된다.



synchronizeList(List<T> list) - list를 동기화된 list로 리턴

synchronizeMap(Map<K, V> map) - map을 동기화된 map으로 리턴

synchronizeSet(Set<T> set) - set을 동기화된 set으로 리턴


ArrayList, HashSet, HashMap이 대표적으로 싱글스레드 기반으로 설계된 컬렉션 클래스인데,

이를 멀티 스레드 환경에서 쓸 수 있도록 컬렉션 프레임워크는 비동기화된 메소드를 동기화된

메소드로 래핑하는 synchronizeXXX( ) 메소를 제공한다.



예제코드


1
2
// 리스트를 동기화된 리스트로 변환
List<T> list = Collections.synchronizedList(new ArrayList<T>());
cs


1
2
// map를 동기화된 map으로 변환
Map<K,V> map = Collections.synchronizedMap(new HashMap<K,V>());
cs


1
2
// set를 동기화된 set으로 변환
Set<T> set = Collections.synchronizedSet(new HashSet<T>());
cs


+ Recent posts