Comment detail

メソッド提供クラスの特定 (Nested Flatten)

Javaでは、Methodの取得の際に自分のクラスに存在するMethodを取得する方法(Class#getDeclaredMethods)と、継承を辿って取得する方法(Class#getMethods)の両方が存在します。 ただし、継承を辿る場合には publicなMethodしか取得できません。

IDEに関しては、eclipseの場合は調べたいMethodの上で、
F3
もしくは
右クリック→宣言を開く

System Message: WARNING/2 (<string>, line 8)

Definition list ends without a blank line; unexpected unindent.

で、実際に呼び出している実装へたどり着けます。

 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
import java.lang.reflect.Method;

public class Sample114 {
    public static void searchMethods(Class<?> target) {
        Method[] declaredMethods = target.getDeclaredMethods();
        System.out.println(target.getName() + " に存在する全てのMethod");
        for (Method m: declaredMethods) {
            System.out.println("\t" + m.toGenericString());
        }

        Method[] methods = target.getMethods();
        System.out.println(target.getName() + " の継承を辿ったpublicなMethod");
        for (Method m: methods) {
            System.out.println("\t" + m.toGenericString());
        }
    }

    public static void main(String[] args) {
        searchMethods(Bar.class);
    }

}

class Foo {
    public void testPublic() {
        System.out.println("public method");
    }
    protected void testProtected() {
        System.out.println("protected method");
    }
    void testPackagePrivate() {
        System.out.println("package private method");
    }
    private void testPrivate() {
        System.out.println("private method");
    }
}

class Bar extends Foo {
    public void testBarPublic() {
        System.out.println("Bar public method");
    }
    protected void testBarProtected() {
        System.out.println("Bar protected method");
    }
    void testBarPackagePrivate() {
        System.out.println("Bar package private method");
    }
    private void testBarPrivate() {
        System.out.println("Bar private method");
    }
}

Index

Feed

Other

Link

Pathtraq

loading...