在java中,如果方法在另一个类中,那么如何让对象在它调用的方法中调用该方法呢?我已经找遍了互联网,也没有解决方案。有没有人能帮帮忙?
发布于 2014-09-19 12:56:02
我能想到的唯一方法是将this传递给该方法,
static void someMethod(Object o) {
System.out.println(o);
}
void testIt() {
someMethod(this); // <-- pass the current instance to the method.
}发布于 2014-09-19 13:01:24
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace()此数组的最后一个元素将是您最近使用的对象。但是更好的方法是使用一个额外的参数,就像上面说的那样,并传递this对象。
发布于 2014-09-19 13:33:04
如果您事先知道需要接收第一个类的实例,那么可以准备第二个类来接收它,如下所示。
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.
}
}如果上面给出的解决方案对你不起作用,这也是可行的。
https://stackoverflow.com/questions/25926606
复制相似问题