2010-10-11 63 views

回答

1

你可以使用'假異常'來做到這一點,即使這個技巧感覺有點骯髒。

try { 
     throw new RuntimeException(); 
    } catch (RuntimeException e) { 
     System.out.println(e.getStackTrace()[1]); 
    } 

getStackTrace返回StackTraceElement對象的數組,你可以檢查API看到你可以與他們做什麼。

+0

你不需要扔掉它,查看我的回答 – 2010-10-11 16:18:47

+0

@ org.life.java謝謝,很高興知道 – 2010-10-11 16:26:37

9
private Class getCallingClass() { 
    return new SecurityManager() { 
     protected Class[] getClassContext(){return super.getClassContext();} 
    }.getClassContext()[2]; 
} 

OR

public class Foo { 

    public static final void main(final String[] args) { 

     test(); 
    } 

    private static void test() { 

     Throwable e = new Throwable(); 

     StackTraceElement[] elements = e.getStackTrace(); 
     System.out.println(elements.length > 1 ? elements[1].toString() : "(no caller)"); 
    } 
} 
+0

我認爲你甚至不需要調用'fillInStackTrace':根據[docs](http:/ /download.oracle.com/javase/1.4.2/docs/api/java/lang/Throwable.html#Throwable%28%29),構造函數會爲你調用它。 – casablanca 2010-10-11 16:20:48

+0

@casablanca耶同意 – 2010-10-11 16:23:53

相關問題