14.反射
通过Java的反射机制,可以更深入地控制程序的运行过程,如再程序运行时对用户输入的信息进行验证,还可以逆向控制程序的执行过程。此外Java在反射机制的基础上,还提供了Annotation功能
14.1Class类与Java反射
java.lang.reflect包中提供了对反射的支持,可以在程序中访问已经装载到JVM中的Java对象的描述,实现访问、检测和修改描述Java对象本身信息的功能。
所有java类均继承了Object类,在Object类中定义了一个getClass()方法,该方法返回某类的一个类型为Class的对象,举例如下:
Class textFieldC=textField.getClass(); //textField为JTextField类的对象
利用Class类的对象textFieldC,可以访问用来返回该对象的textField对象的 描述信息,常用的描述星系如下所示:
方法 | 返回值 | 功能描述 |
---|---|---|
getPackage() | Package对象 | 获得该类的存放路径 |
getName() | String对象 | 获得该类的名称 |
getSuperclass() | Class对象 | 获得该类的父类 |
getInterface() | Class型数组 | 获得该类实现的所有接口 |
getConstructors() | Constructor型数组 | 获得所有权限为public的构造方法 |
getConstructor(Class…parameterTypes) | Constructor对象 | 获得权限为public的构造方法 |
getDeclaredConstructors() | Constructor型数组 | 获得所有构造方法,按申明顺序返回 |
getDeclaredConstructor(Class…parameterTypes) | Constructor对象 | 获得指定构造方法 |
getMethods() | Method型数组 | 获得所有权限为public的方法 |
getMethod(String name,Class…parameterTypes) | Method对象 | 获得指定方法 |
getDeclaredMethods() | Method型数组 | 获得所有方法,按申明顺序返回 |
getDeclaredMethods(String name,Class…parameterTypes) | Method对象 | 获得指定方法 |
getFields() | Field型数组 | 获得所有权限为public的成员变量 |
·getField(String name) | Field对象 | 获得权限为public的指定成员变量 |
getDeclaredFields() | Field型数组 | 获得所有权限为public的成员变量 |
getDeclaredField(String name) | Field对象 | 获得指定成员变量 |
getClasses() | Class型数组 | 获得所有权限为public的内部类 |
getDeclaredClass() | Class型对象 | 获得所有内部类 |
getDeclaringClass() | Class对象 | 如果该类为内部类,则返回它的成员类,否则返回null |
getFiled()和getMethods()方法依次获得权限为public的成员变量和方法时,包括从超类中继承到的成员变量和方法;而方法getDeclaredFields()和getDeclaredMethods()只是获得在本类中定义的所有成员变量和方法。
14.1.1访问构造方法
通过下列一组方法访问构造方法时,将返回Constructor类型的对象或者数组,每个Constructor对象代表一个构造方法,利用Constructor对象可以操纵相应构造方法。
getConstructors()
getConstructor(Class
objectClass.getDeclaredConstructor(String.class,int.class)
objectClass.getDeclaredConstructor(new Class[]{String.class,int.class})
Constructor类中提供的常用方法如下表:
方法 | 功能描述 |
---|---|
isVarArgs() | 查看该构造方法是否允许带有可变数量的参数,如果允许则返回true,否则返回false |
getParameterTypes() | 按照声明顺序以Class数组的形式获得该构造方法的各个参数类型 |
getExceptionTypes() | 以Class数组的形式获得该构造方法可能抛出的异常类型 |
newInstance(Obejct..,.initargs) | 通过该构造方法利用指定参数创建一个该类的对象,未设置参数则表示采用默认无参数构造方法 |
setAccessible(bollean flag) | 当构造方法权限为private时,不允许直接使用newInstance(Obejct…initargs)方法创建对象,需要先执行该方法将参数入口设置为true |
getModifiers() | 获得可以解析该构造方法所采用修饰符的参数 |
通过java.lang.reflect.Modifier类可以解析出getMOdifiers()方法的返回值所表示的修饰符信息,在该类中提供了一系列用来解析的静态方法,既可以查看该构造方法是否被指定的修饰符修饰,还可以以字符串的形式获得所有修饰符,该类常用静态方法如下:
静态方法 | 功能描述 |
---|---|
isPublic(int mod) | 查看是否被public修饰符修饰,如果是则返回true,否则返回false |
isProtected(int mod) | 查看是否被protected修饰符修饰,如果是则返回true,否则返回false |
isPrivate(int mod) | 查看是否被private修饰符修饰,如果是则返回true,否则返回false |
isStatic(int mod) | 查看是否被static修饰符修饰,如果是则返回true,否则返回false |
isFinal(int mod) | 查看是否被final修饰符修饰,如果是则返回true,否者返回false |
toString(int mod) | 以字符串的形式返回所有修饰符 |
例如,判断对象constructor所代表的构造方法是否被private修饰,以及以字符串形式获得该构造方法的所有修饰符的典型代码如下:
int modifiers=constructor.getModifiers();
boolean isEmbellishByPrivate=Modifier.isPrivate(modifiers);
String embellishment=Modifier.toString(modifiers);
以下是一个访问构造方法的实例:
以下是一个Example_01类,该类中声明了3个构造方法:
import java.lang.reflect.Constructor;
public class Main_01 {
public static void main(String[] args) {
Example_01 example=new Example_01("10","20","30");
Class<? extends Example_01>exampleC=example.getClass();
//返回一个Example_01类的Class类对象
//泛型中的<?>表示不确定类型
Constructor[]declaredConstructors=exampleC.getDeclaredConstructors();
//获得所有构造方法
for(int i=0;i<declaredConstructors.length;i++){
Constructor<?>constructor=declaredConstructors[i];
System.out.println("查看是否允许带有可变数量的参数:"+constructor.isVarArgs());
System.out.println("该构造方法的入口参数类型依次为:");
Class[] parameterTypes=constructor.getParameterTypes();
//获得所有参数类型
for(int j=0;j<parameterTypes.length;j++){
System.out.println(" "+parameterTypes[j]);
}
System.out.println("该构造方法可能抛出的异常类型为: ");
//获得所有可能抛出的异常信息类型
Class[]exceptionTypes=constructor.getExceptionTypes();
for(int j=0;j<exceptionTypes.length;j++){
System.out.println(" "+exceptionTypes[j]);
}
Example_01 example2=null;
//在主方法最早的循环中,不同的i值对应不同的构造方法
while(example2==null){
try{//如果该成员变量的访问权限为private,则抛出异常,即不允许访问
if(i==2)//通过执行默认没有参数的构造方法创建对象
{
example2 = (Example_01) constructor.newInstance();
}else if(i==1)
example2=(Example_01)constructor.newInstance("7",5);
else{
Object[]parameters=new Object[]{new String[]{"100","200","300"}};
//思考,为何去掉new String[]后构造方法会出现异常
example2=(Example_01)constructor.newInstance(parameters);
}
}catch(Exception e){
System.out.println("在创建对象时抛出异常,下面执行setAccessible()方法");
constructor.setAccessible(true);
//设置为允许访问
}
}
if(example2!=null){
example2.print();
System.out.println();
}
}
}
}
执行结果分别如下图:
14.1.2访问成员变量
下列方法将返回field类型的对象或者数组。每个Field对象代表一个成员变量。
getFileds()
getField(String name)
getDeclaredFields()
getDeclaredField(String name)对于指定的成员变量,可以通过该成员变量的名称来访问:
object.getDeclaredField("birthday")
Field类中常用方法如下表所示:
方法 | 功能描述 |
---|---|
getName() | 获得该成员变量名称 |
getType() | 获得表示该成员变量类型的Clas对象 |
get(Object obj) | 获得指定对象obj中成员变量的值,返回值为Object类型 |
set(Object obj,Object value) | 将指定对象obj中的成员变量的值设置为value |
getInt(Object) | 获得指定对象obj中类型为int的成员变量的值 |
setInt(Object obj,int i) | 将指定对象obj中类型为int的成员变量的值设置为i |
getFloat(Object obj) | 获得指定对象obj中类型为float的成员变量的值 |
setFloat(Object obj,float f) | 将指定对象obj中类型为float的成员变量的值设置为f |
getBoolean(Object obj) | 获得指定对象obj中类型为Boolean的成员变量的值 |
setBoolean(Object obj,boolean z) | 将指定对象obj中类型为boolean的成员变量的值设置为z |
setAccessible(boolean flag) | 此方法可以设置是否忽略权限限制,直接访问private等私有权限的成员变量 |
getModifiers() | 获得可以解析出该成员变量所采用的修饰符的整数 |
实操如下,首先创建一个Example_02类。
public class Example_02 {
int i;
public float f;
protected boolean b;
private String s;
}
而后通过反射访问并修改Exampel_02类中的成员变量,具体代码如下:
import java.lang.reflect.Field;
public class Main_02 {
public static void main(String[] args) {
Example_02 example=new Example_02();
Class exampleC=example.getClass();
//获得所有成员变量
Field[] declaredFields=exampleC.getDeclaredFields();
for(int i=0;i<declaredFields.length;i++){
//遍历成员变量
Field field=declaredFields[i];
//Field代表一个成员变量,可以方法用来获取和修改变量信息
System.out.println("名称为:"+field.getName());
Class fieldType=field.getType();
//Class类对象可以调用equals()方法判断当前对象类型
System.out.println("类型为:"+fieldType);
boolean isTurn=true;
while(isTurn){
//如果该成员变量的访问权限为private,即不允许访问,则抛出异常
try{
isTurn=false;
System.out.println("修改前值为:"+field.get(example));
//思考,为何参数是类本身?调用者不是已经是确定对象的确定成员变量了吗
//判断成员变量的类型是否为int型
if(fieldType.equals(int.class)){
System.out.println("利用方法setInt()修改成员变量的值");
field.setInt(example,168);
//为int型成员变量赋值
}else if(fieldType.equals(float.class)){
System.out.println("利用方法setFloat()修改成员变量的值");
field.setFloat(example,99.9F);
}else if(fieldType.equals(boolean.class)){
System.out.println("利用方法setBoolean()修改成员变量的值");
field.setBoolean(example,true);
}else{
System.out.println("利用方法set()修改成员变量的值");
field.set(example,"MWQ");
}
System.out.println("修改后值为"+field.get(example));
}catch(Exception e){
System.out.println("在设置成员变量值时抛出异常,"+"下面执行setAccessible()方法!");
field.setAccessible(true);
//设置为允许访问
isTurn =true;
}
}
System.out.println();
}
}
}
对于访问权限为private的成员变量,需要先执行setAccessible()放,将入口参数设置为true,否则不允许访问。
14.1.1访问方法
下列一组方法将返回Method类型的对象或者数组,每个Method对象代表一个方法。
getMethods()
getMethods(String name,Class
import java.lang.reflect.Method;
public class Example_03 {
static void satticMethod() {
System.out.println("执行staticMethod()方法");
}
public int publicMethod(int i) {
System.out.println("执行publicMethod()方法");
return i * 100;
}
protected int protectedMethod(String s, int i) throws NumberFormatException {
System.out.println("执行protectedMethod()方法");
return Integer.valueOf(s) + i;
}
private String privateMethod(String... strings) {
System.out.println("执行privateMethod()方法");
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < strings.length; i++) {
stringBuffer.append(strings[i]);
}
return stringBuffer.toString();
}
}
接着创建一个Main_03类,测试Example_03类的方法名称、入口参数类型、返回值类型等
import java.lang.reflect.Method;
public class Main_03 {
public static void main(String[] args) {
Example_03 example = new Example_03();
Class exampleC = example.getClass();
Method[] declaredMethods = exampleC.getDeclaredMethods();
for (int i = 0; i < declaredMethods.length; i++) {
Method method = declaredMethods[i];
System.out.println("名称为:" + method.getName());
System.out.println("是否允许带有可变数量的参数:" + method.isVarArgs());
System.out.println("入口参数类型为:");
//获得所有参数类型
Class[] parameterTypes = method.getParameterTypes();
for (int j = 0; j < parameterTypes.length; j++) {
System.out.println(" " + parameterTypes[j]);
}
//获得方法返回值类型
System.out.println("返回值类型为" + method.getReturnType());
System.out.println("可能抛出的异常类型有:");
//获得方法可能抛出的所有异常类型
Class[] exceptionTypes = method.getExceptionTypes();
for (int j = 0; j < exceptionTypes.length; j++) {
System.out.println(" " + exceptionTypes[j]);
}
boolean isTurn = true;
while (isTurn) {
//若该方法访问权限为private,即不允许方法,则抛出异常
try {
isTurn = false;
if ("staticMethod".equals(method.getName()))
System.out.println("返回值类型为:" + method.invoke(example));
else if ("publicMethod".equals(method.getName()))
System.out.println("返回值类型为:" + method.invoke(example, 176));
else if ("protectedMethod".equals(method.getName()))
System.out.println("返回值类型为:" + method.invoke(example, "123", 4));
else if ("privateMethod".equals(method.getName())) {
Object[] parameters = new Object[]{new String[]{"M", "W", "Q"}};
//定义二维数组
System.out.println(method.invoke(example, parameters));
}
} catch (Exception e) {
System.out.println("在执行方法时抛出异常,下面执行setAccessible()方法!");
method.setAccessible(true);
isTurn = true;
}
}
System.out.println();
}
}
}
ps:在反射中执行具有可变数量的参数的构造方法时,需要将入口参数定义为二维数组。
14.2Annotation功能
Annotation功能可以用于类、构造方法、成员变量、方法、参数等的声明中。该功能不影响程序的运行,但是会对编译器警告等辅助工具产生影响。
14.2.1定义Annotation类型
定义Annotation类型的关键字为@interface,这个关键字的隐含意思是继承了java.lang.annotaion.Annotaion接口,举例如下:
public @interface NoMemberAnnotation{
}
该Annotation类型@NoMemberAnnotation未包含任何成员变量,这样的Annotation类型被称为marker Annotation,下面的代码定义了只含一个成员的Annotation类型:
public @interface OneMemberAnnotation{
String value();
}
String:成员类型。可以用的成员类型有String、Class、primitive、enumerated和annotation,以及上述类型的数组。
value:成员名称。如果在所定义的Annotation类型中只包含一个成员,通常命名为value.。
以下是一个定义了包含多个成员的Annotation类型。
public @interface MoreMemberAnnotation{
String describle();
Class type();
}
在为Annotation类型定义成员时,也可以为成员设置默认值。举例如下:
public @interface DefalutValueAnnotation{
String describe() default"<默认值>";
Class type() default void class;
}
定义Annotatio类型时,还可以通过Annotation类型@target来设置Annotation类型使用的程序元素种类。如果未设置@Target,则表示适用于所有程序元素。枚举类ElementType中的枚举常量用来设置@Targer,如表所示:
枚举常量 | 功能说明 |
---|---|
ANNOTATION_TYPE | 表示用于Annotation类型 |
TYPE | 表示用于类、接口和枚举,以及Annotation类型 |
CONSTRUCTOR | 表示用于构造方法 |
FIELD | 用于表示成员变量和枚举常量 |
METHOD | 用于表示方法 |
PARAMETER | 用于表示参数 |
LOCAL_VARIABLE | 用于表示局部变量 |
PACKAGE | 用于表示包 |
通过Annotation类型@Retention可以设置Annotation的有效范围。枚举类型RetentionPlicy中的枚举常量用来设置@Retention,如下表所示。如果未设置@Rectention,Annotation的有效范围为枚举常量CLASS表示的范围。
枚举常量 | 功能说明 |
---|---|
SOURCE | 表示不编译Annotation到类文件中,有效范围最小 |
CLASS | 表示编译到Annotation到类文件中,但是运行时不加载Annotation到JVM中 |
RUNTIME | 表示在运行时加载Annotaton到JVM中,有效范围最大 |
定义并使用Annotation类型,举例如下:
首先定义一个用来注释构造方法的Annotation类型@Constructor_Annotation,有效范围在运行时加载Annotation到JVM中,完整代码如下:
import java.lang.annotation.*;
@Target(ElementType.CONSTRUCTOR)
//用于构造方法
@Retention(RetentionPolicy.RUNTIME)
public @interface Constructor_Annotation {
String value() default "默认构造方法";
//定义一个具有默认值的String型成员
}
然后定义一个用来注释字段、方法、参数的Annotation类型@Feild_Method_Parameter_Annotation,有效范围在运行时加载Annotation到JVMzhong ,完整代码如下:
import java.lang.annotation.*;
//用于字段、方法和参数
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
//在运行时加载Annotation到JVM中
public @interface Field_Method_Paramter_Annotation {
String describe();//定义一个没有默认值的String成员
Class type() default void.class;//定义一个具有默认值的Class型成员
}
最后,编写一个Record类,在该类中运用之前定义的Annotaton类型@Constructor_Annotation和@Feild_Method_Parameter_Annotation对构造方法、字段、方法和参数进行注释:
public class Record {
@Field_Method_Paramter_Annotation(describe = "编号", type = int.class)
//注释字段
int id;
@Field_Method_Paramter_Annotation(describe = "姓名", type = String.class)
String name;
@Constructor_Annotation()
//采用默认值注释构造方法
public Record() {
}
@Constructor_Annotation("立即初始化构造方法")
public Record(//注释构造方法
@Field_Method_Paramter_Annotation(describe = "编号", type = int.class) int id,
@Field_Method_Paramter_Annotation(describe = "姓名",type = String.class) String name) {
this.id = id;
this.name = name;
}
@Field_Method_Paramter_Annotation(describe = "获得编号", type = int.class)
public int getId() {//注释构造方法
return id;
}
@Field_Method_Paramter_Annotation(describe = "设置编号")
public void setIdf(//成员type采用默认值注释方法
//注释方法的参数
@Field_Method_Paramter_Annotation(describe = "编号",
type = int.class) int id) {
this.id = id;
}
@Field_Method_Paramter_Annotation(describe = "获得姓名", type = String.class)
public String getName() {
return name;
}
@Field_Method_Paramter_Annotation(describe = "设置姓名")
public void setName(
@Field_Method_Paramter_Annotation(describe = "姓名",
type = String.class) String name) {
this.name = name;
}
public static void main(String[] args) {
}
}
14.2.2访问Annotation信息
如果在定义Annotation类型时将@Retention设置为RetentionPolicy.RUNTIME,那么在运行程序时通过反射就可以获得到相关的Annotation信息,如获取构造方法、字段和方法的Annotation信息。
类Constructor、Field和Method均继承了AccessibleObject类,在AccessibleObject中定义了3个关于Annotation的方法:
方法 | 功能说明 |
---|---|
isAnnotationPresent(ClassannotationClass) | 查看是否添加了指定类型的Annotation,如果是则返回true,否则返回false |
getAnnotation(ClassannotationClass) | 用来获得指定类型的Annotation,如果存在则返回相应的对象,否则返回null |
getAnnotations() | 用来获得所有的Annotation,返回一个Annotation数组 |
在类Constructor和Method中还定义了方法getParameterAnnotations(),用来获得所有为参数添加的Annotation,将以Annotation类型的二维数组返回,在数组中方的顺序与声明的顺序相同,如果没有参数则会返回一个长度为0的数组;如果存在未添加Annotation的参数,将用一个长度为0的嵌套数组占位。
访问Annotation信息的代码举例如下,写入上一段代码中的主方法中即可使用。
以下是编写访问构造方法及其包含参数的Annotation信息 的代码:
public static void main(String[] args) {
Class recordC = new Record().getClass();
//recordC为一个Rrcord类的Class对象
Constructor[] declaredConstructors = recordC.getDeclaredConstructors();
for (int i = 0; i < declaredConstructors.length; i++) {
Constructor constructor = declaredConstructors[i];
//查看是否具有指定类型的注释
if (constructor.isAnnotationPresent(Constructor_Annotation.class)) {
//获得指定类型的注释
Constructor_Annotation ca = (Constructor_Annotation) constructor
.getAnnotation(Constructor_Annotation.class);
System.out.println(ca.value());
//获得注释信息
}
Annotation[][] parameterAnnotations = constructor
.getParameterAnnotations();
//获得参数的注释
for(int j=0;j<parameterAnnotations.length;j++){
//获得指定参数注释的长度
int length=parameterAnnotations[j].length;
if(length==0)
System.out.println(" 未添加Annotation的参数");
else
for(int k=0;k<length;k++){
//获得参数注释
Field_Method_Parameter_Annotation pa=
(Field_Method_Parameter_Annotation)
parameterAnnotations[j][k];
System.out.print(" "+pa.describe());
System.out.println(" "+pa.type());
}
}
System.out.println();
}
}
然后编写访问字段的Annotation信息的代码。完整代码如下:
public static void main(String[] args) {
Class recordC = new Record().getClass();
Field[] declaredFields = recordC.getDeclaredFields();
for (int i = 0; i < declaredFields.length; i++) {
Field field = declaredFields[i];
//查看是否具有指定类型的注释
if (field.isAnnotationPresent(
Field_Method_Parameter_Annotation.class)) {
//获得指定类型的注释
Field_Method_Parameter_Annotation fa = field
.getAnnotation(Field_Method_Parameter_Annotation.class);
System.out.print(" " + fa.describe());
System.out.println(" " + fa.type());
}
}
}
编写访问方法及其包含参数的Annotation信息的代码如下:
public static void main(String[] args) {
Class recordC = new Record().getClass();
Method[] methods = recordC.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
//查看是否具有指定类型的注释
if (method.isAnnotationPresent(Field_Method_Parameter_Annotation.class)) {
//获得指定类型的注释
Field_Method_Parameter_Annotation ma = method
.getAnnotation(Field_Method_Parameter_Annotation.class);
System.out.println(ma.describe());
System.out.println(ma.type());
}
Annotation[][] parameterAnnotations = method
.getParameterAnnotations(); //获得参数的注释
for (int j = 0; j < parameterAnnotations.length; j++) {
int length = parameterAnnotations[j].length;
if (length == 0)
System.out.println(" 未添加Annotation的参数");
else
for (int k = 0; k < length; k++) {
//获得指定类型的注释
Field_Method_Parameter_Annotation pa =
(Field_Method_Parameter_Annotation)
parameterAnnotations[j][k];
System.out.println(" " + pa.describe());//获得参数的描述
System.out.println(" " + pa.type());//喝的参数的类型
}
}
System.out.println();
}
}
14.3小节
java的反射机制可以在程序运行时访问类的所有描述信息
而Annotation功能,可以对代码进行注释,在程序运行时通过反射读取这些信息,根据读取的信息也可以实现逆向控制程序的执行过程。