简介:
所以,我正在使用一个 API,我需要覆盖 2 个 100% 相同的函数,一个返回 byte[],一个返回 short[]。为了确保我不必两次编辑所有内容,我想创建一个返回所需函数的函数。但要实现这一点,我需要创建一个 byte[4096] 或 short[4096],它们不能转换为任何东西,所以我考虑使用反射并检查是否需要 byte[] 或 short[]。
问题:
我不知道如何使用反射创建固定大小的 byte[],所以我就在这里问这个问题。
解决方案:
Array.newInstance(byte.class, size); // new byte[size];
Array.newInstance(byte.class, size, size); // new byte[size][];
Array.newInstance(byte.class, size1, size2); // new byte[size1][size2];
最佳答案
只需使用 java.lang.reflect.Array.newInstance
:
Object byteArray = Array.newInstance(byte.class, 4096)
Object shortArray = Array.newInstance(short.class, 4096);
您可以使用Array
中的其他方法来操作数组。
关于java - 如何使用反射创建具有大小的 byte[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35523059/