[英]Accessing Private Member Without Public Accessor in Java
我遇到了一个挑战,我必须从外部队列类(项目是私有的)获得给定索引的列表项的值。 我不允许修改类,也不允许使用Reflection。 是否有可能(在实际情况下,我宁愿创建公共访问器来获取项目值)?
class Queue {
private List<Integer> items;
private Queue() {
items = new ArrayList<Integer>();
}
public static Queue create() {
return new Queue();
}
public void push(int item) {
items.add(item);
}
public int shift() {
return items.remove(0);
}
public boolean isEmpty() {
return items.size() == 0;
}
}
您可以 :
shift
从Queue
删除所有元素 ArrayList
ArrayList
并使用push
以相同的顺序将元素重新添加到Queue
,以便将Queue
恢复到其原始状态。 ArrayList
的index
'th元素。 这是非常低效的,但它解决了你的挑战。
你可以试试这个
public class TestQueue {
public static void main(String[] args){
Queue q= Queue.create();
q.push(10);
q.push(20);
q.push(30);
q.push(40);
q.push(50);
System.out.println(q.shift());
}}
以上源代码是Queue的基本实现。 根据您的问题,我了解您要提取给定索引的项目。 我认为你应该迭代数据以获得更好的索引。 如果在找到该索引之前到达数组的末尾,则可以抛出ArrayIndexOutOfBoundsException
异常。
这是一个基本的实现。
public void dataRetrieve() throws ArrayIndexOutOfBoundsException {
Queue queue = Queue.create();
queue.push(10);
queue.push(20);
queue.push(30);
queue.push(40);
queue.push(50);
int indexToRetrieve = 5;
int index = 0;
while(!queue.isEmpty()) {
int value = queue.shift();
if (index == indexToRetrieve) {
System.out.println(value);
return;
}
index++;
}
throw new ArrayIndexOutOfBoundsException();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.