集册 Java实例教程 通过反射增加数组大小

通过反射增加数组大小

欢马劈雪     最近更新时间:2020-01-02 10:19:05

492
通过反射增加数组大小

import java.io.BufferedReader;// 来 自 时代Java - N o w  J a v a . c o m

import java.io.CharArrayReader;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.lang.reflect.Field;

import java.util.Arrays;

import static java.lang.System.out;


public class GrowBufferedReader {

    private static final int srcBufSize = 10 * 1024;

    private static char[] src = new char[srcBufSize];

    static {

        src[srcBufSize - 1] = 'x';

    }

    private static CharArrayReader car = new CharArrayReader(src);


    public static void main(String... args) {

        try {/*来 自 时 代 J a v a 公 众 号 - nowjava.com*/

            BufferedReader br = new BufferedReader(car);


            Class<?> c = br.getClass();

            Field f = c.getDeclaredField("cb");


            // cb is a private field

            f.setAccessible(true);

            char[] cbVal = char[].class.cast(f.get(br));


            char[] newVal = Arrays.copyOf(cbVal, cbVal.length * 2);

            if (args.length > 0 && args[0].equals("grow"))

                f.set(br, newVal);


            for (int i = 0; i < srcBufSize; i++)

                br.read();


            // see if the new backing array is being used

            if (newVal[srcBufSize - 1] == src[srcBufSize - 1])

                out.format("Using new backing array, size=%d%n",

                        newVal.length);

            else

                out.format("Using original backing array, size=%d%n",

                        cbVal.length);


            // production code should handle these exceptions more gracefully

        } catch (FileNotFoundException x) {

            x.printStackTrace();

        } catch (NoSuchFieldException x) {

            x.printStackTrace();

        } catch (IllegalAccessException x) {

            x.printStackTrace();

        } catch (IOException x) {

            x.printStackTrace();

        }

    }

}


展开阅读全文