2013-03-02 71 views
1

我已经阅读了很多关于反射的文章,所有的例子都是简单的字符串访问对象,double和int等。 但是,我想访问像Widget,Text甚至自定义对象的对象。 我尝试了与字符串相同的方式,但失败。

例如
我可以访问小部件,文本对象的私人领域吗?

class testPrivate{ 
    public boolean test() 
    { 
     return true; 
    } 

} 

class button { 
public button(){ 
    anc=new testPrivate(); 
} 
    private testPrivate anc; 

} 


public class Testing { 

    public static void main(String arg[]) throws Throwable{ 
    button bt=new button(); 
    Field field = bt.getClass().getDeclaredField("anc"); 
    field.setAccessible(true); 
    System.out.println(field.test()); 
    } 

} 

这里,field.test()在声明中的System.out.println(field.test());失败。

回答

0

Field是指类型的字段,而不是该类的任何特定实例。

为了调用方法,您首先需要该类的实例,然后您必须确保anc不为空。

例子:

button bt=new button(); 
Field field = bt.getClass().getDeclaredField("anc"); 
field.setAccessible(true); 

//This sets the field value for the instance "bt" 
field.set(bt, new testPrivate()); 

然后为了调用该方法,你需要得到该对象,并调用方法对象:

//Since field corresponds to "anc" it will get the value 
//of that field on whatever object you pass (bt in this example). 
testPrivate tp = (testPrivate) field.get(bt); 
System.out.println(tp.test()); 

而且在文体笔记,类应以大写字母开头,例如buttonButtontestPrivateTestPrivate