gpt4 book ai didi

java - 我可以访问小部件、文本对象的私有(private)字段吗?

转载 作者:行者123 更新时间:2023-12-01 04:49:51 25 4
gpt4 key购买 nike

我已经读过很多关于反射的文章,所有的例子都只是简单的字符串、 double 和整数等访问对象。但是,我想访问像 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());失败。

最佳答案

Field 是一个类,它引用 class 类型上的字段,而不是该类的任何特定实例。

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

示例:

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

另外在风格上,类应该以大写字母开头,例如按钮按钮testPrivateTestPrivate

关于java - 我可以访问小部件、文本对象的私有(private)字段吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15175342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com