文章目录
反射与注解
反射
通过java反射机制,可以在程序中访问已经装载到JVM中的java对象的描述,实现访问、检测和修改描述java对象本身信息的功能。java反射机制的功能十分强大,在java.lang.reflect包中提供了对该功能的支持
访问构造函数
在通过下列一组方法访问构造方法时,将返回Constructor类型的对象或数组。每个Constructor对象代表一个构造方法,利用Constructor对象可以操纵相应的构造方法;
Constructor类的常用构造方法
方法 | 说明 |
---|---|
isVarArgs() | 查看该构造方法是否允许带有可变参数,如果允许则返回true,否则返回false |
getParameterType() | 按照声明顺序以Class数组的形式获得该构造方法的各个类型参数 |
getExceptionType() | 以Class数组的形式获得该构造方法的各个参数类型 |
newInstance(Object…initargs) | 通过该构造方法利用指定参数创建一个该类的对象,如果未设置参数则表示采用默认无参的构造方法 |
setAccessible(boolean flag) | 如果该构造方法的权限为private,默认未不允许通过反射利用newInstance(Object…initargs)方法创建对象。那么,先执行该方法并将入口参数设为true,则允许创建 |
getModifiers() | 获得可以解析出该构造方法所采用修饰符的整数 |
Modifier类中的常用解析方法
通过java.lang.reflect.Modifier类可以解析出getModifiers()方法的返回值所表示的修饰符信息,在该类中提供了一系列用来解析的静态方法,既能查看是否被指定的修饰符修饰,又能以字符串的形式获得所有修饰符。Modifier类常用静态方法如下所示
静态方法 | 说明 |
---|---|
isPublic(int mod) | 查看是否被public修饰符修饰,如果是则返回true,否则返回false |
isPratected(int mod) | 查看是否被protected修饰符修饰,如果是则返回true,否则返回false |
isPrivate(int mod) | 查看是否被private修饰符修饰,如果是则返回true,否则返回false |
isStatic(int mod) | 查看是否被static修饰符修饰,如果是则返回true,否则返回false |
isFinal(int mod) | 查看是否被final修饰符修饰,如果是则返回true,否则返回false |
isString(int mod) | 以字符串的形式返回所有修饰符 |
例子:反射一个类的所有构造方法
//Demo1.java
public class Demo1 {
String s;
int i, i2 ,i3;
private Demo1(){
}
protected Demo1(String s,int i){
this.s = s;
this.i = i;
}
public Demo1(String ... strings) throws NumberFormatException {
if(0 < strings.length)
i = Integer.valueOf(strings[0]);
if(1 < strings.length)
i2 = Integer.valueOf(strings[1]);
if(2 < strings.length)
i3 = Integer.valueOf(strings[2]);
}
public void print() {
System.out.println("s=" + s);
System.out.println("i=" + i);
System.out.println("i2=" + i2);
System.out.println("i3=" + i3);
}
}
//Constructor.java
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class ConstructorDemo1 {
public static void main(String[] args) {
Demo1 d1 = new Demo1("10","20","30");
Class<? extends Demo1> Demo1Class = d1.getClass();
//获取所有构造方法
Constructor[] declaredConstructors = Demo1Class.getDeclaredConstructors();
for(int i = 0;i < declaredConstructors.length;i ++){ // 遍历构造方法
Constructor<?>constructor = declaredConstructors[i];
System.out.println("查看是否允许带有可变数量的参数:" + constructor.isVarArgs());
System.out.println("该构造方法的入口参数类型依次为:");
Class[] parameterType = constructor.getParameterTypes();
for(int j = 0;j < parameterType.length;j ++){
System.out.println(" " + parameterType[j]);
}
System.out.println("该构造方法可能抛出的异常类型为:");
// 获得所有可能抛出的异常信息
Class[] exceptionTypes = constructor.getExceptionTypes();
for(int j = 0;j < exceptionTypes.length;j ++){
System.out.println(" " + exceptionTypes[j]);
}
Demo1 d2 = null;
while(d2 == null){
try {
if(i == 2)
d2 = (Demo1)constructor.newInstance();
else if(i == 1)
d2 = (Demo1)constructor.newInstance("7",5);
else{
Object[] parameters = new Object[]{new String[]{"100","200","300"}};
d2 = (Demo1)constructor.newInstance(parameters);
}
} catch (Exception e) {
System.out.println("在创建对象时抛出异常,下面执行setAccessible()方法");
constructor.setAccessible(true);
}
}
if(d2 != null){
d2.print();
System.out.println();
}
}
}
}
访问成员变量
在通过下列一组方法访问成员变量时,将返回Field类型的对象或数组。每个Field对象代表一个成员变量,利用Field对象可以操纵相应的成员变量。
Field类中提供的常用方法
方法 | 说明 |
---|---|
getName() | 获取该成员变量的名称 |
getType() | 获得表示该成员变量类型的Class对象 |
get(Object obj) | 获得指定对象obj中成员变量的值,返回值为Object型 |
set(Object obj,Object value) | 将指定对象obj中成员变量的值设置为value |
getInt(Object obj) | 获得指定对象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() | 获得可以解析出该成员变量所采用修饰符的整数 |
例子
//Demo.java
public class Demo2 {
int i;
public float f;
protected boolean b;
private String s;
}
//FieldDemo2.java
import java.lang.reflect.Field;
public class FieldDemo2 {
public static void main(String[] args) {
Demo2 example = new Demo2();
Class exampleC = example.getClass();
Field[] declaredFields = exampleC.getDeclaredFields(); // 获取所有成员变量
for (int i = 0; i < declaredFields.length; i++) { // 遍历成员变量
Field field = declaredFields[i];
System.out.println("名称为" + field.getName()); // 获取成员变量名称并输出
Class fieldType = field.getType(); // 获取成员变量的类型
System.out.println("类型为" + fieldType);
boolean isTurn = true;
while (isTurn) {
// 如果该成员变量的访问权限是private或者protected,则抛出异常,即不允许访问
try {
isTurn = false;
// 获得成员变量值
System.out.println("修改前值为" + field.get(example));
if (fieldType.equals(int.class)) { // 判断成员变量的值是否为int型
System.out.println("利用方法setInt()修改成员变量的值");
field.setInt(example, 168); // 为int型成员变量赋值
} else if (fieldType.equals(float.class)) { // 判断成员变量的值是否为float类型
System.out.println("利用方法setFloat()修改成员变量的值");
field.setFloat(example, 99.9F); // 为float类型的成员变量赋值ֵ
// 判断成员变量的值是否为boolean类型
} else if (fieldType.equals(boolean.class)) {
System.out.println("利用方法setBoolean()修改成员变量的值");
field.setBoolean(example, true); // 为Boolean类型的成员变量赋值
} 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();
}
}
}
访问成员方法
在通过下列一组方法访问成员方法时,将返回Method类型的对象或数组。每个Method对象代表一个方法,利用Method对象可以操纵相应的方法。
Method类的常用方法
方法 | 说明 |
---|---|
getName() | 获得该方法的名称 |
getParameterType() | 按照声明顺序以Class数组的形式获得该方法的各个参数类型 |
getReturnType() | 以Class对象的形式获得该方法的返回值的类型 |
getExceptionTypes() | 以Class对数组的形式获得该方法可能抛出的异常类型 |
invake(Object obj,Object…args) | 利用指定参数args执行指定对象obj中的该方法,返回值为Object型 |
isVarArgs() | 查看该方法是否允许带有可变数量的参数,如果允许则返回true,否则返回false |
getModifiers() | 获得可以解析出该方法所采用的修饰符的整数 |
// Demo3.java
package com.mr;
public class Demo3 {
static void staticMethod() {
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();
}
}
// MethondDemo.java
import java.lang.reflect.*;
public class MethondDemo {
public static void main(String[] args) {
Demo3 demo = new Demo3();
Class demoClass = demo.getClass();
// 获得所有方法
Method[] declaredMethods = demoClass.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) {
try {// 如果该方法的访问权限为private,则抛出异常,即不允许访问
isTurn = false;
if ("staticMethod".equals(method.getName()))
method.invoke(demo); // 执行没有入口参数的方法
else if ("publicMethod".equals(method.getName()))
System.out.println("返回值为:" + method.invoke(demo, 168)); // 执行方法
else if ("protectedMethod".equals(method.getName()))
System.out.println("返回值为:" + method.invoke(demo, "7", 5)); // 执行方法
else if ("privateMethod".equals(method.getName())) {
Object[] parameters = new Object[] { new String[] { "M", "W", "Q" } }; // 定义二维数组
System.out.println("返回值为:" + method.invoke(demo, parameters));
}
} catch (Exception e) {
System.out.println("在执行方法时抛出异常," + "下面执行setAccessible()方法!");
method.setAccessible(true); // 设置为允许访问
isTurn = true;
}
}
System.out.println();
}
}
}
注解
java中提供了Annotation注解功能,该功能可用于类、构造方法、成员变量、成员方法、参数等的声明中。该功能并不影响程序中的运行,但是会对编辑器警告等辅助工具产生影响。
定义Annotation类型
在定义Annotation类型时,也需要用到用力爱定义接口的interface关键字,但需要在interface关键前加一个“@”符号,即定义Annotation类型的关键字为@interface,这个关键字的隐含意思是继承了java.lang.annotation.Annotation接口。
枚举类ElementType中的枚举常量
枚举常量 | 说明 |
---|---|
ANNOTATION_TYPE | 表示用于Annotation类型 |
TYPE | 表示用于类、接口和枚举,以及Annotation类型 |
CONSTRUCTOR | 表示用于构造方法 |
FIELD | 表示用于成员变量和枚举常量 |
METHOD | 表示用于方法 |
PARAMETER | 表示用于参数 |
LOCAL_VARIABLE | 表示用于局部变量 |
PACKAGE | 表示用于包 |
枚举类RetentionPolicy中的枚举常量
枚举常量 | 说明 |
---|---|
SOURCE | 表示不编译Annotation到类文件中,有效范围最小 |
CLASS | 表示编译Annotation到类文件中,但是在运行不加载Annotation到JVM中 |
RUNTIME | 表示在运行时加载Annotation到JVM中,有效范围最大 |
例子
// 创建自定义注解
// Constructor_Annotation.java
import java.lang.annotation.*;
@Target(ElementType.CONSTRUCTOR)
// 用于构造方法
@Retention(RetentionPolicy.RUNTIME)
// 在运行时加载Annotation到JVM中
public @interface Constructor_Annotation {
String value() default "默认构造方法"; // 定义一个具有默认值的String型成员
}
// Field_Method_Parameter_Annotation
import java.lang.annotation.*;
// 用于字段、方法和参数
@Target( { ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
// 在运行时加载Annotation到JVM中
public @interface Field_Method_Parameter_Annotation {
String describe(); // 定义一个没有默认值的String型成员
Class type() default void.class; // 定义一个具有默认值的Class型成员
}
// Record
public class Record {
@Field_Method_Parameter_Annotation(describe = "编号", type = int.class)
// 注释字段
int id;
@Field_Method_Parameter_Annotation(describe = "姓名", type = String.class)
String name;
@Constructor_Annotation()
// 采用默认值注释构造方法
public Record() {
}
@Constructor_Annotation("立即初始化构造方法")
// 注释构造方法
public Record(@Field_Method_Parameter_Annotation(describe = "编号", type = int.class) int id,
@Field_Method_Parameter_Annotation(describe = "姓名", type = String.class) String name) {
this.id = id;
this.name = name;
}
@Field_Method_Parameter_Annotation(describe = "获得编号", type = int.class)
// 注释方法
public int getId() {
return id;
}
@Field_Method_Parameter_Annotation(describe = "设置编号")
// 成员type采用默认值注释方法
public void setId(
// 注释方法的参数
@Field_Method_Parameter_Annotation(describe = "编号", type = int.class) int id) {
this.id = id;
}
@Field_Method_Parameter_Annotation(describe = "获得姓名", type = String.class)
public String getName() {
return name;
}
@Field_Method_Parameter_Annotation(describe = "设置姓名")
public void setName(@Field_Method_Parameter_Annotation(describe = "姓名", type = String.class) String name) {
this.name = name;
}
}
访问Annotation信息
如果在定义Annotation类型时将@Retention设置为RetentionPolicy.RUNTIME,那么在运行程序时通过反射就可以获取相关的Annotation信息,如获取构造方法、字段和方法的Annotation信息。
例子
// 访问注释中的信息
// AnnotationTest.java
import java.lang.annotation.*;
import java.lang.reflect.*;
public class AnnotationTest {
public static void main(String[] args) {
Class recordC = null;
try {
recordC = Class.forName("Record");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("------ 构造方法的描述如下 ------");
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) // 如果长度为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();
}
System.out.println();
System.out.println("-------- 字段的描述如下 --------");
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()); // 获得字段的类型
}
}
System.out.println();
System.out.println("-------- 方法的描述如下 --------");
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) // 如果长度为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();
}
}
}
// Constructor_Annotation.java
import java.lang.annotation.*;
@Target(ElementType.CONSTRUCTOR)
// 用于构造方法
@Retention(RetentionPolicy.RUNTIME)
// 在运行时加载Annotation到JVM中
public @interface Constructor_Annotation {
String value() default "默认构造方法"; // 定义一个具有默认值的String型成员
}
// Field_Method_Parameter_Annotation.java
import java.lang.annotation.*;
// 用于字段、方法和参数
@Target( { ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
// 在运行时加载Annotation到JVM中
public @interface Field_Method_Parameter_Annotation {
String describe(); // 定义一个没有默认值的String型成员
Class type() default void.class; // 定义一个具有默认值的Class型成员
}
// Record.java
public class Record {
@Field_Method_Parameter_Annotation(describe = "编号", type = int.class)
int id;
@Field_Method_Parameter_Annotation(describe = "姓名", type = String.class)
String name;
@Constructor_Annotation()
public Record() {
}
@Constructor_Annotation("立即初始化构造方法")
public Record(@Field_Method_Parameter_Annotation(describe = "编号", type = int.class) int id,
@Field_Method_Parameter_Annotation(describe = "姓名", type = String.class) String name) {
this.id = id;
this.name = name;
}
@Field_Method_Parameter_Annotation(describe = "获得编号", type = int.class)
public int getId() {
return id;
}
@Field_Method_Parameter_Annotation(describe = "设置编号")
public void setId(@Field_Method_Parameter_Annotation(describe = "编号", type = int.class) int id) {
this.id = id;
}
@Field_Method_Parameter_Annotation(describe = "获得姓名", type = String.class)
public String getName() {
return name;
}
@Field_Method_Parameter_Annotation(describe = "设置姓名")
public void setName(@Field_Method_Parameter_Annotation(describe = "姓名", type = String.class) String name) {
this.name = name;
}
}