第十六章 反射与注解

news/2024/10/25 19:37:04/

 

目录

16.1 反射

1.使用getClass()方法

2.使用.class属性

3.使用class类的forname方法

16.1.2  访问成员变量

16.2  Annotation注解功能

16.2.1  定义Annotation类型

16.2.2 访问Annotation 信息

 


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 的对象。例如下面的代码:

JTextField textField = new JTextFieldO);   //创建 JTextField 对象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 修饰,以及以字符串形式获得该构造

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

int modifiers = constructor.getModifiers();boolean isEmbellishByPrivate = Modifier.isPrivate(modifiers);String embelishment = Modifier.toString(modifiers);

 例题16.1

 
package com.mr;
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() {// TODO Auto-generated method stubSystem.out.println("s=" + s);System.out.println("i=" + i);System.out.println("i2=" + i2);System.out.println("i3=" + i3);}
}
//例题16.1
import java.lang.reflect.Constructor;
import com.mr.Demo1;public class ConstructorDemo1 {public static void main(String[] args) {Demo1 d1 = new Demo1("10", "20", "30");Class<? extends Demo1> demoClass = d1.getClass();// 获得所有构造方法Constructor[] declaredConstructors = demoClass.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]);}Demo1 d2 = null;try { // 如果该成员变量的访问权限为private,则抛出异常,即不允许访问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();}}}
}
//例题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

package com.mr;public class Demo2 {int i;public float f;protected boolean b;private String s;
}
//例题16.2

 

import java.lang.reflect.Field;
import com.mr.Demo2;public class FieldDemo {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,则抛出异常,即不允许访问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();}}
}
//例题16.2

运行结果如下:

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中。完整代码如下:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Target(ElementType.CONSTRUCTOR)			//用于构造方法
@Retention(RetentionPolicy.RUNTIME)			//在运行时加载Annotation到JVM中
public @interface Constructor_Annotation {String value() default "默认构造方法";	//定义一个具有默认值的String型成员
}

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

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

 
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;}
}

16.2.2 访问Annotation 信息

例题16.5

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的参数");elsefor (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的参数");elsefor (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();}}
}
//例题16.5

运行结果如下:

 


http://www.ppmy.cn/news/1199985.html

相关文章

keil代码编辑区配色方案

第一步找到global.prop文件打开 ### 第二步复制下面的文本替换global.prop的内容&#xff0c;保存。 # properties for all file types indent.automatic1 virtual.space0 view.whitespace0 view.endofline0 code.page936 caretline.visible1 highlight.matchingbraces1 prin…

Ubuntu下Anaconda安装

Ubuntu下Anaconda安装 进入anaconda官网 https://www.anaconda.com/ 下载Linux64位版本&#xff1b; 将下载好的".sh"文件放入虚拟机中&#xff1b; 运行指令sudo bash Anaconda3-2023.09-0-Linux-x86_64.sh 此后会自动加载安装程序&#xff0c;中途会停止两次&am…

MR混合现实情景实训教学系统在外语课堂中的应用演示

MR混合现实情景实训教学系统是一种将虚拟现实&#xff08;VR&#xff09;和增强现实&#xff08;AR&#xff09;技术相结合的先进教学工具。它能够为学生提供身临其境的学习环境&#xff0c;使学生能够在模拟的真实场景中进行外语学习。这种教学系统不仅能够帮助学生在实践中提…

应用软件安全编程--05预防 XML 注入

如果用户有能力使用结构化XML 文档作为输入&#xff0c;那么他能够通过在数据字段中插入 XML 标签来 重写这个 XML 文档的内容。 XML 解析器会将这些标签按照正常标签进行解析。下面是一段在线商 店的 XML 代码&#xff0c;主要用于查询后台数据库。 <item)<descri…

操作系统——逻辑结构 vs 物理结构(王道视频 p63)

1.总体概述&#xff1a; 其实&#xff0c;就是讲述了一件事情&#xff0c; 文件内的内容结构——其实完全由用户定义&#xff0c;在操作系统看来&#xff0c;就是“bit串” 文件的物理结构&#xff0c;就是说这个“bit串”整体在操作系统的控制下怎么存储在外存中

flutter项目引入本地静态图片资源并展示

想要在flutter中引入静态资源&#xff0c;需要配置pubspec.yaml&#xff0c;将本地的静态资源添加到assets下面&#xff1a; 然后在flutter引入这些静态资源&#xff1a; Image.asset("images/squick.png") 就可以在app中看到这个图片了&#xff1a; 也可以使用网…

软考 系统架构设计师系列知识点之系统架构评估(8)

接前一篇文章&#xff1a;软考 系统架构设计师系列知识点之系统架构评估&#xff08;7&#xff09; 所属章节&#xff1a; 第8章. 系统质量属性与架构评估 第2节. 系统架构评估 8.2.2 系统架构评估方法 相关试题 7. 架构权衡分析方法&#xff08;Architecture Tradeoff Analy…

数据可视化:动态柱状图

终于来到最后一个数据可视化的文章拿啦~~~ 在这里学习如何绘制动态柱状图 我先整个活 (๑′ᴗ‵๑)&#xff29; Lᵒᵛᵉᵧₒᵤ❤ 什么是pyecharts&#xff1f; 答&#xff1a; Python的Pyecharts软件包。它是一个用于Python数据可视化和图表绘制的库&#xff0c;可用于制作…