java2018. 7. 9. 17:28
1
2
3
4
5
6
7
8
9
10
//Get class name from object
public void getClassNameFromObject(){
 
    Foo f = new Foo();
    try {
        Log.d(TAG, f.getClass().getName());
    } catch ( Exception e){
        Log.d(TAG, ""+e);
    }
}
1
--09 16:48:30.784 12379 12379 D hello   : com.test.simpletest.Foo
1
2
3
4
5
6
7
8
9
10
11
12
//Invoke method on unknown object
public void invokeMethod(){
 
    Foo f = new Foo();
    Method m;
    try {
       m= f.getClass().getMethod("printFoo",new Class<!--?-->[0]);
       m.invoke(f);
    } catch ( Exception e){
        Log.d(TAG, ""+e);
    }
}
1
07-09 16:48:30.784 12379 12379 D hello   : Foo!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//Create object from Class instance
    public void createObjectFromClassInstance(){
 
        Class<!--?--> c = null;
        Foo f = null;
        //create instance of Class
        try {
            c = Class.forName("com.test.simpletest.Foo");
        } catch ( Exception e){
            Log.d(TAG, ""+e);
        }
        //Create instance of Foo
        try {
            f = (Foo) c.newInstance();
        } catch ( Exception e){
            Log.d(TAG, ""+e);
        }
        f.printFoo();
    }
    
1
07-09 16:53:33.591 12766 12766 D hello   : Foo!
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
//Get constructor and create instance
    public void getConstructorAndCreateInstance(){
 
        Class<!--?--> c = null;
 
        //create instance of Class
        try {
            c = Class.forName("com.test.simpletest.Foo");
        } catch ( Exception e){
            Log.d(TAG, ""+e);
        }
        //Create instance of Foo
        Foo f1 = null;
        Foo f2 = null;
 
        Constructor<!--?--> cons[] = c.getConstructors();
 
        //get all constructors
        try {
            f1 = (Foo) cons[0].newInstance();
            f2 = (Foo) cons[1].newInstance("Foo!");
        } catch ( Exception e){
            Log.d(TAG, ""+e);
        }
        f1.printS();
        f2.printS();
    }
    
1
2
07-09 17:19:04.317 14200 14200 D hello   : null
07-09 17:19:04.317 14200 14200 D hello   : Foo!


 출처 : https://www.javacodegeeks.com/2013/09/java-reflection-tutorial.html


'java' 카테고리의 다른 글

반복문에서 label의 사용  (0) 2019.09.12
hashcode 및 equals를 같이 override 하는 이유  (0) 2018.09.06
Cloneable interface (LINK)  (0) 2018.07.18
접근 지정자  (0) 2018.07.18
install openjdk-8-jdk on unbuntu  (0) 2018.06.22
Posted by easy16