2016-05-01 12 views
1

:この割り当てにJavaのリフレクション出力

Write a method displayMethodInfo (as a method of a class of your choosing), with the following signature: static void displayMethodInfo(Object obj); The method writes, to the standard output, the type of the methods of obj. Please format the method type according to the example below. Let obj be an instance of the following class:

class A { 
    void foo(T1, T2) { ... } 
    int bar(T1, T2, T3) { ... } 
    static double doo() { ... } 
} 

The output of displayMethodInfo(obj) should be as follows:

foo (A, T1, T2) -> void 
bar (A, T1, T2, T3) -> int 
doo() -> double 

As you can see, the receiver type should be the first argument type. Methods declared static do not have a receiver, and should thus not display the class type as the first argument type.

私の作業コードは次のとおりです。

import java.lang.Class; 
import java.lang.reflect.*; 

class Main3 { 

    public static class A { 
     void foo(int T1, double T2) { } 
     int bar(int T1, double T2, char T3) { return 1; } 
     static double doo() { return 1; } 
    } 

    static void displayMethodInfo(Object obj) 
    { 
     Method methodsList[] = obj.getClass().getDeclaredMethods(); 
     for (Method y : methodsList) 
     { 
      System.out.print(y.getName() + "(" + y.getDeclaringClass().getSimpleName()); 
      Type[] typesList = y.getGenericParameterTypes(); 
      for (Type z : typesList) 
       System.out.print(", " + z.toString()); 
      System.out.println(") -> " + y.getGenericReturnType().toString()); 
     } 
    } 

    public static void main(String args[]) 
    { 
     A a = new A(); 
     displayMethodInfo(a); 
    } 
} 

これは動作しますが、私の出力は次のようになります。

foo(A, int, double) -> void 
bar(A, int, double, char) -> int 
doo(A) -> double 

出力を尋ねられるように見えるようにするにはどうすればよいですか?

+0

あなたがやったのはなぜ'A'のメソッドのパラメータを' int'、 'double'、' char'と宣言することに決めましたか?明らかに、代入の 'T1'、' T2'と 'T3'は、パラメータの*名前*ではなく、*型*でなければなりません。前提条件が間違っている場合は、結果が間違っているのも当然です... – Holger

+0

ところで、java.lang.Classに 'import'を追加する必要はありません... – Holger

答えて

1

私が正しく理解しているのであれば、唯一の問題は静的なdoo()メソッドの最初のパラメータとしてクラス型を持つことだけです。

あなたはこれをチェックするModifier.isStatic()メソッドを使用できます

 boolean isStatic = Modifier.isStatic(y.getModifiers()); 
    System.out.print(y.getName() + "(" 
         + (isStatic ? "" : y.getDeclaringClass().getSimpleName())); 

あなたは、追加カンマを取り除く必要があるでしょうが、これはハードにすべきではない;)

+0

私はこれを組み込もうとすると、私はエラーが発生します:文字列は、この行でブール値に変換することはできません:System.out.print(y.getName()+ "(" + "isStatic?" ":y.getDeclaringClass()。getSimpleName())); – JMV12

+0

私は2つの括弧を忘れて - テスト版で私の答えを更新しました。 –

関連する問題