prev
next

함수와 메소드의 차이

Posted by epicdev Archive : 2013. 4. 18. 00:02

여태껏 함수와 메소드, 변수와 필드등의 용어들을 혼재해서 막 써왔었는데 이번 기회에 확실하게 기억해 놓아야 겠습니다.

아래의 표를 보시면 각 객체지향언어에서 멤버 변수와 멤버 함수들을 어떻게 지칭하는지 알 수 있습니다.


출처: http://blog.naver.com/cdincdin?Redirect=Log&logNo=30129625682



  
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
package testpackage;
 
import java.lang.reflect.Method;
 
public class ReflectionTest {
     
    public static void main(String[] args) {
        Callee callee = new Callee();
        Method methodA;
        Method methodB;
        Method methodC;
        try {
            methodA = Callee.class.getMethod("printA", String.class);
            methodB = Callee.class.getMethod("printB");
            methodC = Callee.class.getMethod("printC", Integer.class, Double.TYPE);
            methodA.invoke(callee, "Test");
            methodB.invoke(callee);
            methodC.invoke(null, 100, 100.0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
class Callee {
     
    public void printA(String str) {
        System.out.println("A is called");
        System.out.println(str);
    }
 
    public void printB() {
        System.out.println("B is called");
    }
     
    public static void printC(Integer n, double d) {
        System.out.println("C is called");
        System.out.println(n);
        System.out.println(d);
    }
}
출력 결과
1
2
3
4
5
6
A is called
Test
B is called
C is called
100
100.0
  
출처: http://stackoverflow.com/questions/160970/how-do-i-invoke-a-java-method-when-given-the-method-name-as-a-string

Java reflection API를 사용하면된다. 

Coding from the hip, it would be something like:

1
2
3
4
5
6
7
8
java.lang.reflect.Method method;
try {
    method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);
} catch (SecurityException e) {
    // ...
} catch (NoSuchMethodException e) {
    // ...
}
The parameters identify the very specific method you need (if there are several overloaded available, if the method has no arguments, only give methodName).

Then you invoke that method by calling

1
2
3
4
5
6
7
8
9
try {
    method.invoke(obj, arg1, arg2,...);
} catch (IllegalArgumentException e) {
    // ...
} catch (IllegalAccessException e) {
    // ...
} catch (InvocationTargetException e) {
    // ...
}
Again, leave out the arguments in .invoke, if you don't have any. But yeah. Read about Java Reflection 
  
 «이전 1  다음»