• java中对于数组的扩充,使用了反射机制


    简介

    java中对于数组的扩充,使用了反射机制

    code

    package com;
    
    import java.lang.reflect.Array;
    import java.util.Arrays;
    
    public class CopyOfTest {
    	public static void main(String[] args){
    		int[] a = {1, 2, 3};
    		a = (int []) goodCopyOf(a, 10);
    		System.out.println(Arrays.toString(a));
    		
    		String[] b = {"Tom", "Dick", "Harry"};
    		b = (String[]) goodCopyOf(b, 10);
    		System.out.println(Arrays.toString(b));
    		
    		System.out.println("The following call will generate an exception");
    		b = (String[]) badCopyOf(b, 10);
    	}
    	public static Object[] badCopyOf(Object[] a, int newLength) {
    		Object[] newArray = new Object[newLength];
    		System.arraycopy(a, 0, newArray, 0, Math.min(a.length, newLength));
    		return newArray;
    	}
    	
    	public static Object goodCopyOf(Object a, int newLength) {
    		Class cl = a.getClass();
    		if(!cl.isArray()) {
    			return null;
    		}
    		Class componentType = cl.getComponentType();
    		int length = Array.getLength(a);
    		Object newArray = Array.newInstance(componentType, newLength);
    		System.arraycopy(a, 0, newArray, 0, Math.min(length, newLength));
    		return newArray;
    	}
    }
    

    自问自答

    QU: badCopyOf 和 goodCopyOf 的核心区别
    AN: 一个返回的是Object[] 一个返回的是 Object。一个不可以强制类型转换, 一个可以类型转换。

    Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
  • 相关阅读:
    字符编码解码
    综合练习[购物车]
    for 循环实例
    数据类型
    字符串格式化输出
    集成开发环境
    while循环实例
    赋值运算符、逻辑运算符、表达式
    if,else语句猜最大值
    计算今天和今天的上一月的日期
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/13408195.html
Copyright © 2020-2023  润新知