2015-02-07 108 views
2

是否可以從匿名類獲取最終參數值?使用反射或其他什麼?從anonynous類獲取參數

這個例子當然所有組成:

final String x = "Param1"; 
final String y = "Param2"; 
ITest<String> iTest = new ITest<String>() { 

    @Override 
    public String execute() { 
     return t.testMethod(x, y); 
    } 

}; 
// Get values or x and y from iTest here? 
+1

感。你沒有做任何事。 – 2015-02-07 00:12:15

+0

您可以創建實例變量來保留傳遞的參數。 – 2015-02-07 00:16:24

+0

@MalikBrahimi你能解釋一下嗎? – KTrum 2015-02-07 00:18:14

回答

1

因此,這是你的代碼:

ITest<String> iTest = new ITest<String>() { 

    @Override 
    public String execute() { 
     return testMethod(x, y); 
    } 

}; 

嘗試定義ITest像這樣:

public class ITest { 
    int x; 
    int y; 

    public testMethod(int x, int y) { 
     this.x = x; this.y = y; 
    } 

    // execute somewhere 
} 
+0

這似乎工作。但是沒有其他辦法可以實現你的想法?'不改變ITest – KTrum 2015-02-07 00:36:20

+0

我不這麼認爲。 – 2015-02-07 00:37:46

1

我沒有嘗試這樣做我自己,但我認爲,xy的值複製到該匿名類的實例自動生成的字段。試試這個:

for (Field field : iTest.getClass().getDeclaredFields()) { 
    field.setAccessible(true); 
    System.out.println(field.getName() + ": " + field.get(iTest)); 
} 
+0

我也這麼認爲,但可悲的是我只得到了運行此代碼的外部類的引用 – KTrum 2015-02-07 00:17:45