如何在 JAVA 中通过调用方法访问调用方对象的成员



这是我的代码

class Base
{
  public void fillRandomData()
  {
    //code for accessing members for sub classes
        //here object "b" is calling this method
        //I want to access members of caller object
        //As it is Derived class how can I access its member 
  }
}
class Derived extends Base
{
  Map<String, List<Integer>> fields = new HashMap<String,List<Integer>>();
  List<Integer> attribute = new ArrayList<Integer>();
    public Derived() {
        attribute.add(1);
        fields.put("textbox",attribute);
    }
}
class Main
{
     public static void main(String[] argv) {
         Base b = new Base();
       **b.fillRandomData();**
     }
}

上面的代码解释了我的问题。我在访问调用方对象成员时陷入困境我认为回顾会有所帮助,但对我帮助不大。

在ruby中有一个方法"instance_variable_get(instance_var)",它允许访问调用者对象的数据成员。

您必须定义方法并将方法调用到中。您不能在类块中调用方法。

像这样:

class Main
{
void callMethod(){
  Base b = new Base ();
  b.fillRandomData();
}
}

根据我对你的问题的理解,你想做一些事情,比如:

class Base
{
  public void fillRandomData()
  {
      // do not directly access members. you can use reflect to do this but do not do this.
      // (unless you have a real reason for it)
      //
      // instead, trust on the subclasses to correctly override fillRandomData to fill in the
  }
}
class Derived extends Base
{
    Map<String, List<Integer>> fields = new HashMap<String,List<Integer>>();
    List<Integer> attribute = new ArrayList<Integer>();
    public Derived() {
        attribute.add(1);
        fields.put("textbox",attribute);
    }
    @Override
    public void fillRandomData() {
         // in Main, the b.fillRandomData will run this method.
         // let the Base class set it's part of the data
         super.fillRandomData();
         // then let this class set it's data
         // do stuff with attributes
         // do stuff with fields.
    }
 }
class Main
{
  // you _must_ instantiate a derived object if you want to have a chance at getting it's instance variables
    public static void main(String[] argv) { 
        Base b = new Derived();
        b.fillRandomData();
    }
}

最新更新