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 * https://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
34 /** The array to wrap. */
35 private final Object array;
36
37 /**
38 * Create the wrapper.
39 *
40 * @param anArray {@link #array}
41 */
42 public ArrayListWrapper(final Object anArray) {
43 if (!anArray.getClass().isArray()) {
44 throw new IllegalArgumentException(anArray.getClass() + " is not an array");
45 }
46 this.array = anArray;
47 }
48
49 @Override
50 public boolean contains(final Object o) {
51 return indexOf(o) != -1;
52 }
53
54 @Override
55 public Object get(final int index) {
56 return Array.get(array, index);
57 }
58
59 @Override
60 public int indexOf(final Object o) {
61 final int size = size();
62 if (o == null) {
63 for (int i = 0; i < size; i++) {
64 if (get(i) == null) {
65 return i;
66 }
67 }
68 } else {
69 for (int i = 0; i < size; i++) {
70 if (o.equals(get(i))) {
71 return i;
72 }
73 }
74 }
75 return -1;
76 }
77
78 @Override
79 public Iterator<Object> iterator() { return new ArrayIterator(array); }
80
81 @Override
82 public Object set(final int index, final Object element) {
83 final Object old = Array.get(array, index);
84 Array.set(array, index, element);
85 return old;
86 }
87 @Override
88 public int size() {
89 return Array.getLength(array);
90 }
91 }