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

时间:2014-11-06 12:47:00

标签: 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中有方法&#34; instance_variable_get(instance_var)&#34;允许访问调用者对象的数据成员。

2 个答案:

答案 0 :(得分:1)

你必须定义方法并调用你的方法,你不能在类块中调用方法。

像这样:

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

答案 1 :(得分:1)

根据我从你的问题中理解你想做的事情:

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();
    }
}