2014-09-19 44 views
0

在java中,如果该方法位于另一个类中,如何在调用的方法内获得调用该方法的对象?我看遍了互联网,没有解决方案。有人可以帮忙吗?获取对象调用方法

+1

没有必要调用方法的对象。如果你从'static'方法或'static'初始化方法调用该方法呢? – 2014-09-19 04:54:03

+3

你为什么需要这些信息? – 2014-09-19 04:56:53

+0

为此创建单例类! – k0sh 2014-09-19 04:57:48

回答

1

我能想到的唯一的办法是通过this的方法,

static void someMethod(Object o) { 
    System.out.println(o); 
} 
void testIt() { 
    someMethod(this); // <-- pass the current instance to the method. 
} 
+0

要访问调用类的实例,他需要有一个已经由第二个类创建的实例来调用调用类的方法。没有?如果是这样,那将是一个不同的例子。我看到的唯一方法是调用类存储自己的静态引用,这很麻烦,但可以让他调用静态方法来获取所需的实例。 – MarGar 2014-09-19 05:07:37

+0

+1虽然不是唯一的方法,但是最好的方法。 – nmore 2014-09-19 05:09:38

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. 
} 

} 

如果上面给出的解决方案不适用于您,这也可以工作。