2014-11-06 80 views
0

这里是我的代码如何通过调用方法访问主叫对象的成员在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();** 
    } 
} 

上面的代码解释了我的问题。 我在访问调用者对象成员stucked 我认为回顾将有所帮助但它并没有帮助我很多。

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

+1

目前尚不清楚你的意思主叫对象成员什么。上面的代码不能编译。也许你可以更详细地描述你实际上想要做什么?或者发布你正在编写的实际代码,而不是伪代码? – Joeblade 2014-11-06 12:54:51

+0

好的,你想从Base部分的代码访问实例Derived部分的成员?这不是建议的做法。尽管如此,还是有办法的。 – Joeblade 2014-11-06 12:57:59

+0

@Joeblade调用者对象的成员表示调用该方法的对象。 在这种情况下,_b.fillRandomData()_“b”是对象我想在此方法中访问“fillRandomData()”中的“b”的成员。 – 2014-11-07 06:01:23

回答

1

您必须定义方法并调用您的方法进入您无法在类块中调用方法。

这样的:

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

这实质上是问题的代码示例 - 没有看到这是一个很好的答案。 – 2014-11-06 13:13:10

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

为了完整性和教育目的,重写方法应该有一个'@覆盖'注释 – 2014-11-06 13:14:07

+0

好点。我是一个糟糕的编码员,很少使用这些编码器,我的编辑为我解决了这类问题。所以手动编写代码让我忘了。 – Joeblade 2014-11-06 13:15:00

相关问题