简体   繁体   English

在Java中访问没有公共访问者的私有成员

[英]Accessing Private Member Without Public Accessor in Java

I've been given a challenge, that I must get value of list item at given index, from outside Queue class (items is private). 我遇到了一个挑战,我必须从外部队列类(项目是私有的)获得给定索引的列表项的值。 I'm not allowed to modify the class, and not allowed to use Reflection. 我不允许修改类,也不允许使用Reflection。 Is it possible (in a real case, I would rather create public accessor to get items value) ? 是否有可能(在实际情况下,我宁愿创建公共访问器来获取项目值)?

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

You can : 您可以 :

  1. remove all the elements from the Queue , using shift 使用shiftQueue删除所有元素
  2. add each removed element to your own ArrayList 将每个已删除的元素添加到您自己的ArrayList
  3. iterate over the ArrayList and re-add the elements to the Queue in the same order using push in order to restore the Queue to its original state. 迭代ArrayList并使用push以相同的顺序将元素重新添加到Queue ,以便将Queue恢复到其原始状态。
  4. return the index 'th element of your ArrayList . 返回ArrayListindex 'th元素。

It's very inefficient, but it solves your challenge. 这是非常低效的,但它解决了你的挑战。

You may try this 你可以试试这个

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

Above source code is a basic implementation of Queue. 以上源代码是Queue的基本实现。 From your question I understand that you want to extract item of a given index. 根据您的问题,我了解您要提取给定索引的项目。 I think you should iterate data to get the preferable index. 我认为你应该迭代数据以获得更好的索引。 If you come to end of array before finding that index then you can throw ArrayIndexOutOfBoundsException exception. 如果在找到该索引之前到达数组的末尾,则可以抛出ArrayIndexOutOfBoundsException异常。

Here is a basic implementation. 这是一个基本的实现。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM