在java中,如果該方法位於另一個類中,如何在調用的方法內獲得調用該方法的對象?我看遍了互聯網,沒有解決方案。有人可以幫忙嗎?獲取對象調用方法
Q
獲取對象調用方法
0
A
回答
1
我能想到的唯一的辦法是通過this
的方法,
static void someMethod(Object o) {
System.out.println(o);
}
void testIt() {
someMethod(this); // <-- pass the current instance to the method.
}
0
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace()
該數組的最後一個元素會在你使用了最新的對象。但是應該更好地使用一個額外的參數,如上所述回答並通過this
對象。
0
如果你事先知道你需要接收第一類的實例,那麼你可以準備第二類來接收它,如下所示。
public class class1 {
public static void main(String[] args)
{
new class1();
}
public class1()
{
send();
}
private void send()
{
new class2().receiveClass(this);// creates an instance of class 2 and sends a reference of class1 (this)
}
public void print()
{
System.out.println("class1.print()");
}
}
要在第二堂課獲得。
public class class2 {
private class1 c1;
public void receiveClass(class1 c)
{
c1=c;
c1.print(); //accessing the print method of class1, the same instance that references this object.
}
}
如果上面給出的解決方案不適用於您,這也可以工作。
相關問題
- 1. 獲取對象方法R
- 2. 獲取對象的方法
- 3. 獲取調用其方法之一的對象的名稱
- 4. 從Memcached中獲取對象的調用方法
- 5. 獲取調用從頁面對象寶石提示方法
- 6. django鉤入對象被調用時獲取方法/對象的更新字段
- 7. 調用方法對象
- 8. 獲取對方法調用者的引用的一般方法?
- 9. 如何從方法內獲得調用方法的對象
- 10. 獲取方法被調用的方法?
- 11. 獲取方法對象而不用按名稱尋址方法
- 12. 獲取LINQ-TO-SQL對象的方法
- 13. 如何獲取方法的Method對象?
- 14. print_r在PHP中獲取對象方法?
- 15. 獲取iframe對象的最佳方法
- 16. 如何獲取方法的父對象?
- 17. 從as3中的方法獲取對象
- 18. 找到在調試器中獲取對象實例的方法?
- 19. 對ListView中的對象調用方法
- 20. JavaScript調用對象語法的方法
- 21. 不使用對象調用類方法?
- 22. 使用ASM的調用對象方法
- 23. 用字符串對象調用方法
- 24. 通用對象調用方法
- 25. Powershell/.Net:獲取對方法返回的對象的引用
- 26. 的JavaScript - 獲取調用對象
- 27. 獲取(指向)調用對象
- 28. 獲取調用事件的對象
- 29. 獲取通用類型的調用動態對象中的方法
- 30. 如何從通用方法獲得的對象調用函數?
沒有必要調用方法的對象。如果你從'static'方法或'static'初始化方法調用該方法呢? – 2014-09-19 04:54:03
你爲什麼需要這些信息? – 2014-09-19 04:56:53
爲此創建單例類! – k0sh 2014-09-19 04:57:48