第十六章 反射与注解

16.1 反射:

1.class类

2.获取构造方法

3.获取成员属性

4.获取成员方法

注解

1.内置注解

2.反射注解

创建Class对象的三种方式

1.使用getClass()方法

object str = new object();

class c = str.getClass()

    Demo1 d1 = new Demo1();
        Class c1 = d1.getClass();

2.使用.class属性

class c = object.class

Class c2 = Demo1.class;

3.使用class类的forname方法

class c = class.forname("全路径")

   Class c3 = Class.forName("com.mr.Demo1");

创建class,包会自动创建

众所周知,所有Java 类均继承了 Object 类,在Object 类中定义了一个 getClassO方法,该方法返

回一个类型为Class 的对象。例如下面的代码:

 
  1. JTextField textField = new JTextFieldO);   //创建 JTextField 对象

  2. Class textFieldC = textField.getClass();  //获取Class对象

利用Class 类的对象 textFieldC,可以访问用来返回该对象的textField对象的描述信息。可以访问

的主要描述信息如表 16.1所示。

16.1.1 访问构造方法 

在通过下列一组方法访问构造方法时,将返回Constructor 类型的对象或数组。每个Constuctor 对象代表一个构造方法,利用Constructor 对象可以操纵相应的构造方法:

  • getConstructors()
  • getConstructor(Class<?>...parameterTypes)
  • getDeclaredConstructors()
  • getDeclaredConstructor(Class<?>..parameterTypes)

如果是访问指定的构造方法,需要根据该构造方法的入口参数的类型来访问。例如,访问一个入口参数类型依次为String型和 int型的构造方法,通过下面两种方式均可实现:

objeciClass.getDeclaredConstructor(String.class, int.class);

objectClass.getDeclaredConstructor(new Classil { String.class, int.class });

Constructor 类中提供的常用方法如表16.2所示。

 Modifier 类中的常用解析方法如下:

例如,判断对象 constructor 所代表的构造方法是否被 private 修饰,以及以字符串形式获得该构造

方法的所有修饰符的典型代码如下:

 
  1. int modifiers = constructor.getModifiers();

  2. boolean isEmbellishByPrivate = Modifier.isPrivate(modifiers);

  3. String embelishment = Modifier.toString(modifiers);

例题16.1

 
  1. package com.mr;

  2. public class Demo1 {

  3. String s;

  4. int i, i2, i3;

  5. private Demo1() {

  6. }

  7. protected Demo1(String s, int i) {

  8. this.s = s;

  9. this.i = i;

  10. }

  11. public Demo1(String... strings) throws NumberFormatException {

  12. if (0 < strings.length)

  13. i = Integer.valueOf(strings[0]);

  14. if (1 < strings.length)

  15. i2 = Integer.valueOf(strings[1]);

  16. if (2 < strings.length)

  17. i3 = Integer.valueOf(strings[2]);

  18. }

  19. public void print() {

  20. // TODO Auto-generated method stub

  21. System.out.println("s=" + s);

  22. System.out.println("i=" + i);

  23. System.out.println("i2=" + i2);

  24. System.out.println("i3=" + i3);

  25. }

  26. }

  27. //例题16.1

 
  1. import java.lang.reflect.Constructor;

  2. import com.mr.Demo1;

  3. public class ConstructorDemo1 {

  4. public static void main(String[] args) {

  5. Demo1 d1 = new Demo1("10", "20", "30");

  6. Class<? extends Demo1> demoClass = d1.getClass();

  7. // 获得所有构造方法

  8. Constructor[] declaredConstructors = demoClass.getDeclaredConstructors();

  9. for (int i = 0; i < declaredConstructors.length; i++) { // 遍历构造方法

  10. Constructor<?> constructor = declaredConstructors[i];

  11. System.out.println("查看是否允许带有可变数量的参数:" + constructor.isVarArgs());

  12. System.out.println("该构造方法的入口参数类型依次为:");

  13. Class[] parameterTypes = constructor.getParameterTypes(); // 获取所有参数类型

  14. for (int j = 0; j < parameterTypes.length; j++) {

  15. System.out.println(" " + parameterTypes[j]);

  16. }

  17. System.out.println("该构造方法可能抛出的异常类型为:");

  18. // 获得所有可能抛出的异常信息类型

  19. Class[] exceptionTypes = constructor.getExceptionTypes();

  20. for (int j = 0; j < exceptionTypes.length; j++) {

  21. System.out.println(" " + exceptionTypes[j]);

  22. }

  23. Demo1 d2 = null;

  24. try { // 如果该成员变量的访问权限为private,则抛出异常,即不允许访问

  25. if (i == 2) // 通过执行默认没有参数的构造方法创建对象

  26. d2 = (Demo1) constructor.newInstance();

  27. else if (i == 1)

  28. // 通过执行具有两个参数的构造方法创建对象

  29. d2 = (Demo1) constructor.newInstance("7", 5);

  30. else { // 通过执行具有可变数量参数的构造方法创建对象

  31. Object[] parameters = new Object[] { new String[] { "100", "200", "300" } };

  32. d2 = (Demo1) constructor.newInstance(parameters);

  33. }

  34. } catch (Exception e) {

  35. System.out.println("在创建对象时抛出异常,下面执行setAccessible()方法");

  36. constructor.setAccessible(true); // 设置为允许访问

  37. }

  38. if (d2 != null) {

  39. d2.print();

  40. System.out.println();

  41. }

  42. }

  43. }

  44. }

  45. //例题16.1

 运行结果如下:

16.1.2  访问成员变量

在通过下列一组方法访问成员变量时,将返回Field 类型的对象或数组。每个Field对象代表一个成员变量,利用Ficld 对象可以操纵相应的成员变量:

  • getFields()
  • getField(String name)
  • getDeclaredFields()
  • getDeclaredField(String name)

如果是访问指定的成员变量,可以通过该成员变量的名称来访问。例如,访问一个名称为birthday的成员变量,访问方法如下:

object. getDeclaredField("birthday");

Field 类中提供的常用方法如表16.4所示。

例题16.2

 
  1. package com.mr;

  2. public class Demo2 {

  3. int i;

  4. public float f;

  5. protected boolean b;

  6. private String s;

  7. }

  8. //例题16.2

 
  1. import java.lang.reflect.Field;

  2. import com.mr.Demo2;

  3. public class FieldDemo {

  4. public static void main(String[] args) {

  5. Demo2 example = new Demo2();

  6. Class exampleC = example.getClass();

  7. // 获得所有成员变量

  8. Field[] declaredFields = exampleC.getDeclaredFields();

  9. for (int i = 0; i < declaredFields.length; i++) { // 遍历成员变量

  10. Field field = declaredFields[i];

  11. System.out.println("名称为:" + field.getName()); // 获得成员变量名称

  12. Class fieldType = field.getType(); // 获得成员变量类型

  13. System.out.println("类型为:" + fieldType);

  14. boolean isTurn = true;

  15. while (isTurn) {

  16. // 如果该成员变量的访问权限为private,则抛出异常,即不允许访问

  17. try {

  18. isTurn = false;

  19. // 获得成员变量值

  20. System.out.println("修改前的值为:" + field.get(example));

  21. if (fieldType.equals(int.class)) { // 判断成员变量的类型是否为int型

  22. System.out.println("利用方法setInt()修改成员变量的值");

  23. field.setInt(example, 168); // 为int型成员变量赋值

  24. } else if (fieldType.equals(float.class)) { // 判断成员变量的类型是否为float型

  25. System.out.println("利用方法setFloat()修改成员变量的值");

  26. field.setFloat(example, 99.9F); // 为float型成员变量赋值

  27. // 判断成员变量的类型是否为boolean型

  28. } else if (fieldType.equals(boolean.class)) {

  29. System.out.println("利用方法setBoolean()修改成员变量的值");

  30. field.setBoolean(example, true); // 为boolean型成员变量赋值

  31. } else {

  32. System.out.println("利用方法set()修改成员变量的值");

  33. field.set(example, "MWQ"); // 可以为各种类型的成员变量赋值

  34. }

  35. // 获得成员变量值

  36. System.out.println("修改后的值为:" + field.get(example));

  37. } catch (Exception e) {

  38. System.out.println("在设置成员变量值时抛出异常," + "下面执行setAccessible()方法!");

  39. field.setAccessible(true); // 设置为允许访问

  40. isTurn = true;

  41. }

  42. }

  43. System.out.println();

  44. }

  45. }

  46. }

  47. //例题16.2

运行结果如下:

16.1.3  访问成员方法

在通过下列一组方法访问成员方法时,将返回Method类型的对象或数组。每个Method对象代表-个方法,利用Method 对象可以操纵相应的方法:

  • getMethods()
  • getMethod(String name, Class<?>...parameterTypes)
  • getDeclaredMethods()
  • getDeclaredMethod(String name, Class<?>...parameterTypes)

如果是访问指定的方法,需要根据该方法的名称和入口参数的类型来访问。例如,访问一个名称为print、入口参数类型依次为String型和int型的方法,通过下面两种方式均可实现:

objectClass.getDeclaredMethod("print",String.class, int.class);

objectClass.getDeclaredMethod("print", new Class[] {String.class, int.class });

Method 类中提供的常用方法如表16.5所示。

例题16.3

 
  1. package com.mr;

  2. public class Demo3 {

  3. static void staticMethod() {

  4. System.out.println("执行staticMethod()方法");

  5. }

  6. public int publicMethod(int i) {

  7. System.out.println("执行publicMethod()方法");

  8. return i * 100;

  9. }

  10. protected int protectedMethod(String s, int i) throws NumberFormatException {

  11. System.out.println("执行protectedMethod()方法");

  12. return Integer.valueOf(s) + i;

  13. }

  14. private String privateMethod(String... strings) {

  15. System.out.println("执行privateMethod()方法");

  16. StringBuffer stringBuffer = new StringBuffer();

  17. for (int i = 0; i < strings.length; i++) {

  18. stringBuffer.append(strings[i]);

  19. }

  20. return stringBuffer.toString();

  21. }

  22. }

  23. //例题16.3

 
  1. import java.lang.reflect.*;

  2. import com.mr.Demo3;

  3. public class MethondDemo {

  4. public static void main(String[] args) {

  5. Demo3 demo = new Demo3();

  6. Class demoClass = demo.getClass();

  7. // 获得所有方法

  8. Method[] declaredMethods = demoClass.getDeclaredMethods();

  9. for (int i = 0; i < declaredMethods.length; i++) {

  10. Method method = declaredMethods[i]; // 遍历方法

  11. System.out.println("名称为:" + method.getName()); // 获得方法名称

  12. System.out.println("是否允许带有可变数量的参数:" + method.isVarArgs());

  13. System.out.println("入口参数类型依次为:");

  14. // 获得所有参数类型

  15. Class[] parameterTypes = method.getParameterTypes();

  16. for (int j = 0; j < parameterTypes.length; j++) {

  17. System.out.println(" " + parameterTypes[j]);

  18. }

  19. // 获得方法返回值类型

  20. System.out.println("返回值类型为:" + method.getReturnType());

  21. System.out.println("可能抛出的异常类型有:");

  22. // 获得方法可能抛出的所有异常类型

  23. Class[] exceptionTypes = method.getExceptionTypes();

  24. for (int j = 0; j < exceptionTypes.length; j++) {

  25. System.out.println(" " + exceptionTypes[j]);

  26. }

  27. boolean isTurn = true;

  28. while (isTurn) {

  29. try {// 如果该方法的访问权限为private,则抛出异常,即不允许访问

  30. isTurn = false;

  31. if ("staticMethod".equals(method.getName()))

  32. method.invoke(demo); // 执行没有入口参数的方法

  33. else if ("publicMethod".equals(method.getName()))

  34. System.out.println("返回值为:" + method.invoke(demo, 168)); // 执行方法

  35. else if ("protectedMethod".equals(method.getName()))

  36. System.out.println("返回值为:" + method.invoke(demo, "7", 5)); // 执行方法

  37. else if ("privateMethod".equals(method.getName())) {

  38. Object[] parameters = new Object[] { new String[] { "M", "W", "Q" } }; // 定义二维数组

  39. System.out.println("返回值为:" + method.invoke(demo, parameters));

  40. }

  41. } catch (Exception e) {

  42. System.out.println("在执行方法时抛出异常," + "下面执行setAccessible()方法!");

  43. method.setAccessible(true); // 设置为允许访问

  44. isTurn = true;

  45. }

  46. }

  47. System.out.println();

  48. }

  49. }

  50. }

  51. //例题16.3

运行结果如下:

16.2  Annotation注解功能

该功能可用于类、构造方法、成员变量、成员方法、参数等的声明中。该功能并不会影响程序的运行,但是会对编译器警告等辅助工具产生影响

16.2.1  定义Annotation类型

内置注解:

  • @Override :限定重写父类方法作用范围成员方法
  • @SuppressWarnings :抑制编译器警告作用范围类、成员属性、成员方法
  • @Deprecated :标示已过时作用范围类、成员属性、成员方法

在定义Annotation 类型时,也需要用到用来定义接口的interface 关键字,但需要在interface关键字前加一个“@”符号,即定义Annotation 类型的关键字为@interface,这个关键字的隐含意思是继承了 java.lang.annotation.Annotation 接口。例如,下面的代码就定义了一个 Annotation 类型:

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 describe();

Class type();

}

在为Annotation 类型定义成员时,也可以为成员设置默认值。例如,下面的代码在定义Annotation

型时就为成员设置了默认值:

public @interface DefaultValueAnnotation

String describe() default "<默认值>";

Class type() default void.class;

}

在定义Annotation 类型时,还可以通过 Annotation 类型@Target 来设置Annotation类型适用的程序元素种类。如果未设置@Target,则表示适用于所有程序元素。枚举类 ElementType 中的枚举常量用来设置@Targer,如表16.6所示

通过 Amotaion 类型@Retenion 可以设置Amnotation 的有效范围。枚举类RetentioPolicy 中的枚举常量用来设置@Rctention, 如表 16.7所示。如果未设置@Retention,Annotation 的有效范围为枚举常量CLASS 表示的范围

例题16.4

首先定义一个用来注释构造方法的Annotation类型@Constructor_Annotation,有效范围为在运行时加载Annotation到JVM中。完整代码如下:

 
  1. import java.lang.annotation.ElementType;

  2. import java.lang.annotation.Retention;

  3. import java.lang.annotation.RetentionPolicy;

  4. import java.lang.annotation.Target;

  5. @Target(ElementType.CONSTRUCTOR) //用于构造方法

  6. @Retention(RetentionPolicy.RUNTIME) //在运行时加载Annotation到JVM中

  7. public @interface Constructor_Annotation {

  8. String value() default "默认构造方法"; //定义一个具有默认值的String型成员

  9. }

然后定义一个用来注释字段、方法和参数的 Annotaion 类型@Field.Method Paranet Anotion

有效范围为在运行时加载 Annotation到JVM中。完整代码如下:

 
  1. import java.lang.annotation.ElementType;

  2. import java.lang.annotation.Retention;

  3. import java.lang.annotation.RetentionPolicy;

  4. import java.lang.annotation.Target;

  5. //用于字段,方法和参数

  6. @Target({ElementType.FIELD,ElementType.METHOD,ElementType.PARAMETER})

  7. @Retention(RetentionPolicy.RUNTIME) //在运行时加载Annotation到JVM中

  8. public @interface Field_Method_Parameter_Annotation {

  9. String describe(); //定义一个没有默认值的String型成员

  10. Class type() default void.class; //定义一个具有默认值的Class型成员

  11. }

最后编写一个 Record类,在该类中运用前面定义的 Annotation 类型@Constructor_Annotation和

@Field Method Parameter_Annotation 对构造方法、字段、方法和参数进行注释。完整代码如下:

 
  1. public class Record {

  2. @Field_Method_Parameter_Annotation(describe = "编号",type = int.class)

  3. //注释字段

  4. int id;

  5. @Field_Method_Parameter_Annotation(describe = "姓名",type = String.class )

  6. String name;

  7. @Constructor_Annotation()

  8. //采用默认值注释构造方法

  9. public Record() {

  10. }

  11. @Constructor_Annotation("立即初始化构造方法")

  12. //注释构造方法

  13. public Record(@Field_Method_Parameter_Annotation(describe = "编号",type = int.class)int id,

  14. @Field_Method_Parameter_Annotation(describe = "姓名",type = String.class)String name) {

  15. this.id = id;

  16. this.name =name;

  17. }

  18. @Field_Method_Parameter_Annotation(describe = "获取编号",type = int.class )

  19. //注释方法

  20. public int getId() {

  21. return id;

  22. }

  23. @Field_Method_Parameter_Annotation(describe = "设置编号")

  24. //成员type采用默认值注释方法

  25. public void setId(

  26. //注释方法的参数

  27. @Field_Method_Parameter_Annotation(describe = "编号",type = int.class )int id) {

  28. this.id = id;

  29. }

  30. @Field_Method_Parameter_Annotation(describe = "获取姓名",type = String.class )

  31. public String getName() {

  32. return name;

  33. }

  34. @Field_Method_Parameter_Annotation(describe = "设置姓名")

  35. public void setName(@Field_Method_Parameter_Annotation(describe = "姓名",type = String.class )String name) {

  36. this.name = name;

  37. }

  38. }

16.2.2 访问Annotation 信息

例题16.5

 
  1. import java.lang.annotation.*;

  2. import java.lang.reflect.*;

  3. public class AnnotationTest {

  4. public static void main(String[] args) {

  5. Class recordC = null;

  6. try {

  7. recordC = Class.forName("Record");

  8. } catch (ClassNotFoundException e) {

  9. e.printStackTrace();

  10. }

  11. System.out.println("------ 构造方法的描述如下 ------");

  12. Constructor[] declaredConstructors = recordC.getDeclaredConstructors(); // 获得所有构造方法

  13. for (int i = 0; i < declaredConstructors.length; i++) {

  14. Constructor constructor = declaredConstructors[i]; // 遍历构造方法

  15. // 查看是否具有指定类型的注释

  16. if (constructor.isAnnotationPresent(Constructor_Annotation.class)) {

  17. // 获得指定类型的注释

  18. Constructor_Annotation ca = (Constructor_Annotation) constructor

  19. .getAnnotation(Constructor_Annotation.class);

  20. System.out.println(ca.value()); // 获得注释信息

  21. }

  22. Annotation[][] parameterAnnotations = constructor.getParameterAnnotations(); // 获得参数的注释

  23. for (int j = 0; j < parameterAnnotations.length; j++) {

  24. // 获得指定参数注释的长度

  25. int length = parameterAnnotations[j].length;

  26. if (length == 0) // 如果长度为0则表示没有为该参数添加注释

  27. System.out.println(" 未添加Annotation的参数");

  28. else

  29. for (int k = 0; k < length; k++) {

  30. // 获得参数的注释

  31. Field_Method_Parameter_Annotation pa = (Field_Method_Parameter_Annotation) parameterAnnotations[j][k];

  32. System.out.print(" " + pa.describe()); // 获得参数描述

  33. System.out.println(" " + pa.type()); // 获得参数类型

  34. }

  35. }

  36. System.out.println();

  37. }

  38. System.out.println();

  39. System.out.println("-------- 字段的描述如下 --------");

  40. Field[] declaredFields = recordC.getDeclaredFields(); // 获得所有字段

  41. for (int i = 0; i < declaredFields.length; i++) {

  42. Field field = declaredFields[i]; // 遍历字段

  43. // 查看是否具有指定类型的注释

  44. if (field.isAnnotationPresent(Field_Method_Parameter_Annotation.class)) {

  45. // 获得指定类型的注释

  46. Field_Method_Parameter_Annotation fa = field.getAnnotation(Field_Method_Parameter_Annotation.class);

  47. System.out.print(" " + fa.describe()); // 获得字段的描述

  48. System.out.println(" " + fa.type()); // 获得字段的类型

  49. }

  50. }

  51. System.out.println();

  52. System.out.println("-------- 方法的描述如下 --------");

  53. Method[] methods = recordC.getDeclaredMethods(); // 获得所有方法

  54. for (int i = 0; i < methods.length; i++) {

  55. Method method = methods[i]; // 遍历方法

  56. // 查看是否具有指定类型的注释

  57. if (method.isAnnotationPresent(Field_Method_Parameter_Annotation.class)) {

  58. // 获得指定类型的注释

  59. Field_Method_Parameter_Annotation ma = method.getAnnotation(Field_Method_Parameter_Annotation.class);

  60. System.out.println(ma.describe()); // 获得方法的描述

  61. System.out.println(ma.type()); // 获得方法的返回值类型

  62. }

  63. Annotation[][] parameterAnnotations = method.getParameterAnnotations(); // 获得参数的注释

  64. for (int j = 0; j < parameterAnnotations.length; j++) {

  65. int length = parameterAnnotations[j].length; // 获得指定参数注释的长度

  66. if (length == 0) // 如果长度为0表示没有为该参数添加注释

  67. System.out.println(" 未添加Annotation的参数");

  68. else

  69. for (int k = 0; k < length; k++) {

  70. // 获得指定类型的注释

  71. Field_Method_Parameter_Annotation pa = (Field_Method_Parameter_Annotation) parameterAnnotations[j][k];

  72. System.out.print(" " + pa.describe()); // 获得参数的描述

  73. System.out.println(" " + pa.type()); // 获得参数的类型

  74. }

  75. }

  76. System.out.println();

  77. }

  78. }

  79. }

  80. //例题16.5

运行结果如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值