2011-01-21 20 views

回答

3

最簡潔的方法是隻傳遞調用者本身或至少一些提示作爲構造函數或方法參數。

Other other = new Other(this); 
// or 
other.doSomething(this); 

討厭的方法是根據堆棧跟蹤解密它。

public void doSomething() { 
    StackTraceElement caller = Thread.currentThread().getStackTrace()[2]; 
    String callerClassName = caller.getClassName(); 
    // ... 
} 
+1

在第二種方法中,唯一捕獲的信息是類名......沒有多大用處。 – adrianboimvaser 2011-01-21 02:30:21

0

除了構造函數,你可以使用靜態初始化塊或初始化塊。

class A 
{ 

    private Object a; 

    { 
     // Arbitrary code executed each time an instance of A is created. 
     System.out.println("Hey, I'm a brand new object!"); 
     System.out.println("I get called independently of any constructor call."); 
    } 

    static 
    { 
     // Arbitrary *static* code 
     System.out.println("Some static initialization code just got executed!"); 
    } 

    public A() 
    { 
     // Plain-Jane constructor 
     System.out.println("You're probably familiar with me already!"); 
    } 
} 

我想我誤解了你的問題,但我會留下我上面寫的。

根據您的要求,您也可以看看AspectJ。它可能提供一個乾淨的方式來實現你的目標。

3

對於一個班級來說,瞭解誰在呼喚它通常被認爲是一個壞主意。它使得設計非常脆弱。也許更好的一個是定義一個接口,任何類都可以符合這個接口作爲方法調用的一部分傳入。然後調用方法可以由類A執行。使它成爲一個接口意味着A沒有對調用它的類的具體知識。

另一種選擇是使用周圍A.一個裝飾然後裝飾可以實現方法調用和做的事情先和後進行轉發調用類A

關於外部API的思考,春天攔截可能是一個好的解決方案

這一切都歸結於你想要做的事情。但我會建議A類做這種事情是一個糟糕的設計理念。

相關問題