2015-07-10 114 views
0

可以說我有一個應用程序:有沒有辦法獲得創建另一個對象的對象的實例?

my_Application the_application = new my_Application(); 
Parser parser = new Parser; 
parser.log(); 

,然後得到一些方法parser.log()拋出一個字符串轉換成應用程序的窗口?

public void log(String input){ 
    // Get the instance of the object which created this object, call it 'daddy' 
    daddy.log(input); 
} 

雖然在原始類my_Application中有一個方法log

public void log(String input){ 
    textPane.append("[LOG] " + input); 
} 
+0

不,甚至可能沒有這樣的例子。考慮它是以靜態方法構建的情況。 – EJP

回答

1

隨着你的代碼站立,你不能。您的parser需要參考the_application。要做到這一點的方法之一是在構造函數中:

public class Parser { 
    private my_Application daddy = null; 
    public Parser(my_Application app) { 
     daddy = app; 
    } 

    public void log(String input){ 
     daddy.log(input); 
    } 
} 

然後你創建瞭解析:

my_Application the_application = new my_Application(); 
Parser parser = new Parser(the_application); 

作爲一個方面,聲明Java類下劃線是不是一種普遍的做法。相反,使用駝峯的約定,如MyApplication

0

不,除非創建的對象持有對其創建者的一些引用。沒有固有的聯繫。

0

我最好的建議是向構造函數提供「daddy」類,並確保它實現了一個具有void log(String input)方法的接口。

interface Logger{ 
    void log(String input); 
} 

public class Parser implements Logger{ 

    Logger parent; 

    public Parser(Logger parent){ 
     this.parent = parent; 
    } 

    void log(String input){ 
     parent.log(input); 
    } 
} 

public class my_Application implements Logger{ 
    void log(String input){ 
     textPane.append("[LOG] " + input); 
    } 

    public static void Main(String[] args){ 
     my_Application the_application = new my_Application(); 
     Parser parser = new Parser(the_application); 
     parser.log(); 
    } 
} 
0

您可以使用堆棧跟蹤來獲取此信息

StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace() 

據的Javadoc:

數組的最後一個元素代表堆棧的底部, 這是序列中最近的方法調用。

甲的StackTraceElement具有getClassName()getFileName()getLineNumber()getMethodName()

的教程

http://www.javaworld.com/article/2072391/the-surprisingly-simple-stacktraceelement.html雖然這個回答你的問題,這不會在要調用父類方法的方式幫助。假設您可以使用reflection,您可以調用該方法。

否則考慮使用

  • 靜態方法
  • 鏈接到父通過使對它的引用調用方法。
  • 繼承?
+0

當然,這隻會在構造函數中工作? – celticminstrel

+0

@celticminstrel你是什麼意思'那個'? –

+0

那麼,創建對象'new Parser()'的方法唯一可以保證在堆棧中的唯一時間是構造函數Parser()',對嗎?你可以從任何地方調用'parser.log()',而不僅僅是'my_Application'的方法。 – celticminstrel

0

最容易的&友好的方式:繼續參考父母。

private Parent parentReference; 
public Child(Parent parent) 
{ 
    this.parentReference = parent; 
} 
相關問題