简体   繁体   中英

Java access the caller variable, is it possible? how?

i have a class

    main {  
      Class1 class1=new Class1();  
      class1.function1(); 
    }


     class Class1 {   
        int abc=1;   
        ArrayList<Class2> class2s=new ArrayList<Class2>(); 

        int function1() {
          class2s.add(new Class2(asd));
          abc=555;   
        }    
     }

     class Class2 {   
        int functionx() {
          Log.e("abc?", ""+PARENT???.abc);   
        } 
     }

How can I get the caller Class's variable, say abc?

By making Class2 an inner, non-static class of Class1 :

class Class1 {   
    int abc=1;   
    ArrayList<Class2> class2s=new ArrayList<Class2>(); 

    int function1() {
      class2s.add(new Class2());
      abc=555;   
    }    

    class Class2 {   
        int functionx() {
            Log.e("abc?", abc);   
        } 
    }
}

Class2 will have a hidden reference to the instance of Class1.

Note Your example has one other mistake, in of that Class2 has no constructor. I have changed new Class2(asd) (which asd was also undefined) to new Class2()

You could pass the caller as an argument, like so:

int functionx(Class1 caller) {
  Log.e("abc?", ""+caller.abc)
}

and call it with

Class2 cls = new Class2()
cls.functionx(this)

As long as abc is visible to Class2. Otherwise there is no direct means of knowing your caller in Java. The variable class2s implements a uni-directional relationship between Class1 and Class2. So you can only navigate from Class1 to Class2, not the other way around.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM