2015-07-02 39 views
0

實例說我有一個名爲MyClass類,這個類中,我想找出實例化MyClass的對象,例如類名:爪哇 - 確定在一個對象從對象的類

class MyClass { 
    final String whoCreatedMe; 
    public MyClass() { 
     whoCreatedMe = ??? 
    } 
} 

public class Driver { 
    public static void main(String[] args) { 
     System.out.println(new MyClass().whoCreatedMe); // should print Driver 
    } 
} 
+2

字符串是不可變的 - 只是沒有任何方法可以讓你改變一個字符串(除非你使用反射 - 並去地獄)。 –

+0

讓我們退一步:你爲什麼認爲你想這樣做?你真正想要解決的問題是什麼? – GhostCat

回答

2

通來電類名在構造函數中..

class MyClass { 
    String whoCreatedMe; 
    public MyClass() { 
    } 
    public MyClass(String mCallerClass) { 
     this.whoCreatedMe = mCallerClass; 
     System.out.println(this.whoCreatedMe+" instantiated me.."); 
    } 
} 

public class Driver { 
    public static void main(String[] args) { 
     System.out.println(new MyClass(this.getClass().getName())); // should print Driver but no quotes should be there in parameter 
    } 
} 
+0

好吧...這個作品,但我不會有問,如果我可以這樣做:) – bohanl

+0

是的..你可以做到這一點..一個錯誤是在我以前的帖子..你應該刪除最後' whoCreatedMe' – Kushal

3

這是不可取的,而且很可能打破在最意想不到的(和預期)的方式。所以我希望你不會在生產代碼中使用它。

public class Temp { 

    static class TestClass { 
     public final String whoCreatedMe; 
     public TestClass() { 
      StackTraceElement ste = Thread.getAllStackTraces().get(Thread.currentThread())[3]; 
      whoCreatedMe = ste.getClassName(); 
     } 
    } 

    public static void main(String[] args) throws Exception { 

     System.out.println(new TestClass().whoCreatedMe); 
    } 
} 
0

在純Java中,您可以嘗試使用堆棧跟蹤來獲取該類信息。當然,你不應該硬編碼2,它可能是很脆弱的,當您使用代理服務器,攔截器等 你可以把這個構造函數

 StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); 
     System.out.println(stackTrace[2].getClassName()); 

至於谷歌可能無法正常工作 - 你在標籤中提到的反射,我不認爲它支持這種操作,因爲這不是反射。

0

我不會建議這種方法,但如果你真的想這樣做,這是一個我能想到的工作示例。

public class Driver { 
    public static void main(String[] args) { 
      System.out.println(new MyClass().whoCreatedMe); // should print Driver 
     } 
} 


public class MyClass { 

    public String whoCreatedMe; 

    public MyClass(){ 
     Exception ex = new Exception(); 
     StackTraceElement[] stackTrace = ex.getStackTrace(); 
     whoCreatedMe = stackTrace[1].getClassName(); 
    } 

}