1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.commons.jexl3.internal.introspection;
18
19 import java.lang.reflect.Array;
20 import java.util.AbstractList;
21 import java.util.Iterator;
22 import java.util.RandomAccess;
23
24 /**
25 * A class that wraps an array within an AbstractList.
26 * <p>
27 * It overrides some methods because introspection uses this class a marker for wrapped arrays; the declared class
28 * for these method is thus ArrayListWrapper.
29 * The methods are get/set/size/contains and indexOf because it is used by contains.
30 * </p>
31 */
32 public class ArrayListWrapper extends AbstractList<Object> implements RandomAccess {
33 /** the array to wrap. */
34 private final Object array;
35
36 /**
37 * Create the wrapper.
38 * @param anArray {@link #array}
39 */
40 public ArrayListWrapper(final Object anArray) {
41 if (!anArray.getClass().isArray()) {
42 throw new IllegalArgumentException(anArray.getClass() + " is not an array");
43 }
44 this.array = anArray;
45 }
46
47 @Override
48 public Object get(final int index) {
49 return Array.get(array, index);
50 }
51
52 @Override
53 public Object set(final int index, final Object element) {
54 final Object old = Array.get(array, index);
55 Array.set(array, index, element);
56 return old;
57 }
58
59 @Override
60 public int size() {
61 return Array.getLength(array);
62 }
63
64 @Override
65 public int indexOf(final Object o) {
66 final int size = size();
67 if (o == null) {
68 for (int i = 0; i < size; i++) {
69 if (get(i) == null) {
70 return i;
71 }
72 }
73 } else {
74 for (int i = 0; i < size; i++) {
75 if (o.equals(get(i))) {
76 return i;
77 }
78 }
79 }
80 return -1;
81 }
82
83 @Override
84 public boolean contains(final Object o) {
85 return indexOf(o) != -1;
86 }
87 @Override
88 public Iterator<Object> iterator() { return new ArrayIterator(array); }
89 }