Java 获取调用方法的对象

Java 获取调用方法的对象,java,class,object,methods,method-call,Java,Class,Object,Methods,Method Call,在java中,如果一个方法在另一个类中,如何在它调用的方法中获得调用该方法的对象?我在互联网上到处找,没有找到解决办法。有人能帮忙吗?我能想到的唯一办法就是把这个传递给方法 static void someMethod(Object o) { System.out.println(o); } void testIt() { someMethod(this); // <-- pass the current instance to the method. } 静态方法(对象o){

在java中,如果一个方法在另一个类中,如何在它调用的方法中获得调用该方法的对象?我在互联网上到处找,没有找到解决办法。有人能帮忙吗?

我能想到的唯一办法就是把这个传递给方法

static void someMethod(Object o) {
  System.out.println(o);
}
void testIt() {
  someMethod(this); // <-- pass the current instance to the method.
}
静态方法(对象o){
系统输出打印ln(o);
}
无效测试(){
someMethod(this);//

此数组的最后一个元素将是您最近使用的对象。但最好使用上面回答的额外参数,并传递
对象。

如果您事先知道需要接收第一个类的实例,则可以按如下方式准备第二个类来接收它

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

}

如果上面给出的解决方案对您不起作用,这也会起作用。

不一定存在调用方法的对象。如果您从
static
方法或
static
初始值设定项调用该方法会怎么样?为什么需要此信息?为此创建Singleton类!获取有关调用的一些信息的一种非常糟糕的方法堆栈将生成一个伪异常并查看它的转储,但不要认为这解决了这个问题。要访问调用类的实例,他需要第二个类已经创建了一个实例才能调用调用类方法。否?如果是这样,它将是另一个实例。我看到的唯一方法是调用class存储自身的静态引用,这很麻烦,但允许他调用静态方法来获得所需的实例。
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.
 }

}