Java Reference
In-Depth Information
Listing 3-15.
Checking for Reflect Permission in a Program
// ReflectPermissionTest.java
package com.jdojo.reflection;
import java.lang.reflect.ReflectPermission;
public class ReflectPermissionTest {
public static void main(String[] args) {
try {
// Create a permission object
ReflectPermission rp = new ReflectPermission("suppressAccessChecks");
// check for permission
rp.checkGuard(null);
System.out.println("Reflect permission is granted");
}
catch (SecurityException e) {
System.out.println("Reflect permission is not granted");
}
}
}
Reflecting on Arrays
Java provides special APIs to work with arrays. The
Class
class lets you find out if a
Class
reference represents an
array by using its
isArray()
method. You can also create an array, and read and modify its element's values using
reflection. The
java.lang.reflect.Array
class is used to dynamically create an array and to manipulate its elements.
As stated before, you cannot reflect on the
length
field of an array using normal reflection procedure. However, the
Array
class provides you the
getLength()
method to get the length value of an array. Note that all methods in the
Array
class are static and most of them have the first argument as the array object's reference on which they operate.
To create an array, use the
newInstance()
static method of the
Array
class. The method is overloaded and it has
two versions.
Object newInstance(Class<?> componentType, int arrayLength)
•
Object newInstance(Class<?> componentType, int... dimensions)
•
One version of the method creates an array of the specified component type and the array length. The
other version creates an array of the specified component type and dimensions. Note that the return type of the
newInstance()
method is
Object
. You will need to use an appropriate cast to assign it to the actual array type.
If you want to create an array of
int
of length 5, you would write
int[] ids = (int[])Array.newInstance(int.class, 5);
The above statement is the same as
Object ids = new int[5];
If you want to create an array of
int
of dimension
5 X 8
, you would write
int[][] matrix = (int[][])Array.newInstance(int.class, 5, 8);