|
| 1 | +package org.javacore.reflection; |
| 2 | + |
| 3 | +import java.lang.reflect.Array; |
| 4 | +import java.util.Arrays; |
| 5 | + |
| 6 | +/* |
| 7 | + * Copyright [2015] [Jeff Lee] |
| 8 | + * |
| 9 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 10 | + * you may not use this file except in compliance with the License. |
| 11 | + * You may obtain a copy of the License at |
| 12 | + * |
| 13 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 14 | + * |
| 15 | + * Unless required by applicable law or agreed to in writing, software |
| 16 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 17 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 18 | + * See the License for the specific language governing permissions and |
| 19 | + * limitations under the License. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @author Jeff Lee |
| 24 | + * @since 2015-11-9 10:45:19 |
| 25 | + * 反射扩容对象数组 |
| 26 | + */ |
| 27 | +public class ArrayCopy { |
| 28 | + public static void main(String[] args) { |
| 29 | + int[] a = {1,2,3}; |
| 30 | + a = (int[]) goodCopyOf(a,10); |
| 31 | + System.out.println(Arrays.toString(a)); |
| 32 | + |
| 33 | + String[] str = {"a","b","c"}; |
| 34 | + str = (String[]) goodCopyOf(str,10); |
| 35 | + System.out.println(Arrays.toString(str)); |
| 36 | + } |
| 37 | + |
| 38 | + public static Object goodCopyOf(Object a,int newLength){ |
| 39 | + // 获取Class对象 |
| 40 | + Class cl = a.getClass(); |
| 41 | + // 如果不是数组对象,则返回null; |
| 42 | + if (!cl.isArray()) return null; |
| 43 | + // 获取数组组件对象 |
| 44 | + Class componentType = cl.getComponentType(); |
| 45 | + int length = Array.getLength(a); |
| 46 | + Object newArray = Array.newInstance(componentType,newLength); |
| 47 | + // 复制数组 |
| 48 | + System.arraycopy(a,0,newArray,0,Math.min(length,newLength)); |
| 49 | + return newArray; |
| 50 | + } |
| 51 | +} |
0 commit comments