I was wondering if it is possible to change to change the length of a class's integer array using the Java Reflection API. If so, how?
问题:
回答1:
Nope; an array is created with a fixed length.
What you can do is get close by modifying the value of the field with a copy in larger array (using Arrays.copyOf
), so long as you know modifying like this won't cause any inconsistency.
/* desired length */
final int desired = ...;
/* the instance of the object containing the int[] field */
final Object inst = ...;
/* the handle to the int[] field */
final Field field = ...;
field.set(inst, Arrays.copyOf((int[]) field.get(inst), desired));
回答2:
I don't think it's possible to change array length even with Reflection.
This is a reference from java tutorial.
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
回答3:
An array is a fixed length data structure, so there is no way that it's length will be modified. Nevertheless, one can create a new array with a new fixed length in such way it can accommodate new members using
System.arrayCopy()
It is like you have an array of type T with the size of 2,
T[] t1 = new T[2]
and it is length is fixed with 2. So it can not store any more than 2 elements. But by creating new array with a new fixed length, say 5,
T[] t2 = new T[5]
So it can accommodate 5 elements now. Now copy the contents of the t1 to t2 using
System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
in this case of the example,
System.arraycopy(t1, 0, t2, 0, t1.length)
Now in the new array, you have position
from t1.length to t2.length-1
is available for you to use.
回答4:
I guess java will not allow you to change array length but yes you can set value at index using reflection.
import java.lang.reflect.*;
public class array1 {
public static void main(String args[])
{
try {
Class cls = Class.forName(
"java.lang.String");
Object arr = Array.newInstance(cls, 10);
Array.set(arr, 5, "this is a test");
String s = (String)Array.get(arr, 5);
System.out.println(s);
}
catch (Throwable e) {
System.err.println(e);
}
}
}