2016-05-01 57 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個括號 - 用一個測試版本更新了我的答案。 –