對反射API的訪問由安全管理器所控制.Field,Method和Constructor類都是由一個名為AccessibleObject的基類擴展的.AccessibleObject類有一個主要的方法,名為setAccessible(),由此可以在訪問特定的類成員時解除平常所設定的安全性.Javadoc說明如下:
setAccessible
public
void setAccessible(boolean flag)
throws
SecurityException
Set the accessible flag for this object to the
indicated boolean value. A value of true indicates that the reflected object
should suppress Java language access checking when it is used. A value of false
indicates that the reflected object should enforce Java language access
checks.
First, if there is a security manager, its checkPermission
method is called with a ReflectPermission("suppressAccessChecks")
permission.
A SecurityException is raised if flag is true but
accessibility of this object may not be changed (for example, if this element
object is a Constructor object for the class Class).
A
SecurityException is raised if this object is a Constructor object for the class
java.lang.Class, and flag is true.
Parameters:
flag - the
new value for the accessible flag
Throws:
SecurityException -
if the request is denied.
See
Also:
SecurityManager.checkPermission(java.security.Permission),
RuntimePermission
Class類提供了兩組方法來得到每一種特性.其中一組允許訪問類的公共特性(其中包括由其超類所繼承得到的成員),而另一組則允許訪問在類中直接聲明的任何公共或非公共成員(而不包括繼承得來的成員),這要取決于有何安全性考慮.以下是一些例子:
.getFields()將返回一個Field對象數組,它表示一個類的所有公共變量,其中包括繼承得到的公共變量.
.getDeclareFields()將返回一個數組,以表示類中聲明的所有變量,而不論其訪問修飾符如何(不包括安全管理器不允許看到的變量),但是不包括繼承得到的變量.
.對于構造函數,"所有構造函數"和"所聲明構造函數"之間無所謂差別(類不會繼承構造函數),因此getConstructors()和getDeclaredConstructors()的唯一區別在于,前者返回的是公共構造函數,而后者則返回類的所有構造函數.