第六章:反射+设计模式

一、反射

  1. 反射(Reflection):允许在程序运行状态中,可以获取任意类中的属性和方法,并且可以操作任意对象内部的属性和方法,这种动态获取类的信息及动态操作对象的属性和方法对应的机制称为反射机制。

  2. 类对象 和 类的对象(实例)

(1)类的对象(实例):基于某个类 new 出来的对象,也称为实例对象。

(2)类对象:类加载的产物,封装了一个类的所有信息(包、类名、父类、接口、属性、方法、构造方法等)

  1. 获取类对象的三种方式:

(1)通过类的对象,获取类对象

Student s = new Student();

class c=s.getclass();

(2)通过类名获取类对象

Classc=类名.class;

(3)通过静态方法获取类对象

Class c=class.forName("包名.类名");

注意:需要 权限类名:包名.类名

public class Testclass {

public static void main(String\[\] args)throws classNotFoundException {

//深入JVM实现原理/JVM规范

// 通过反射技术 获取 类对象

Students= new student(); // 类的对象,实例

Class c=s.getclass();//获取类对象

System.out.println(c);

//第二种方式:

Class c2=Class.forName("testflect.student");

System.out.println(c2);

System.out.printin(c==c2);

Class c3= Student.class;

System.out.println(c3);

}

}

4.反射常见的方法:

Class c= class.forName("testflect.student");

// 动态 操作类中信息

system.out.println(c.getName());// 获取类名

System.out.printin(c.getPackage().getName());// 获取包名

System.out.printin(c.getsuperclass().getName());// 获取父类

C1ass\[\]cs=c.getInterfaces();// 获取 实现的接口

System.out.print1n("实现的接口数量为:"+cs.length);

for(class inter:cs){

System.out.println(inter.getName());

}

Method\[\]ms=c.getMethods();//获取公开方法:自定义+父类中

System.out.printin("student类定义的方法数量为:"+ms.length);

for(Method m:ms){

System.out.printin(m.getName());

}

System.out.printin("-----------------");

Method\[\]mds =c.getDeclaredMethods();//获取自定义方法,包含非公开的

System.out.print]n("student类中自定义的方法为:"+mds.1ength);

for(Method m:mds){

System.out.printIn(m.getName());

}

System.out.printin("获取属性:");

Field\[\]fs =c.getDeclaredFields();// 获取自定义属性:包含非公开的

for (Field f:fs){

System.out.printIn(f.getName());

}

通过反射技术获取实例:

// 通过类对象 获取 类的对象

---采用无参数的构造方法获取对象

Class c= class.forName("testflect.student");

0bject obj=c.newInstance(); //默认采用无参数的构造方法

Student s=(Student)obj;

s.setName("佳明");

s.setAge(28);

s.setscore(99.0);

system.out.printin(obj);

采用有参数的构造方法获取对象

System.out.printin("利用有参数的构造方法获取对象:");

Constructor con=c.getconstructor(string.class,Integer.class,Double.class);

0bject obj2=con.newInstance("杨浩",37,88.0);

System.out.printin(obj2);

//利用反射技术操作私有化的方法

Method md=c.getDeclaredmethod("test");

md.setAccessible(true);

md.invoke(obj2);

相关推荐
青禾网络1 天前
Web 前端如何接入 AI 音效生成:从零到可用的完整方案
人工智能·设计模式
ZJPRENO2 天前
吃透软件开发六大设计原则,告别烂代码
设计模式
咖啡八杯2 天前
GoF设计模式——命令模式
java·设计模式·架构
花椒技术3 天前
HJPusher / HJPlayer SDK 实践:我们为什么把直播推播链路拆成一套可复用能力
设计模式·harmonyos·直播
艺艺生辉3 天前
迭代器模式-"我也想被增强for循环"
设计模式
咖啡八杯5 天前
GoF设计模式——策略模式
java·后端·spring·设计模式
槑有老呆6 天前
别再手搓 Prompt 了,那个叫"手动挡循环"
设计模式
用户6919026813397 天前
Vibe Coding 开发项目的基本范式
人工智能·设计模式·代码规范
怕浪猫8 天前
领域特定语言(Domain-Specific Language, DSL)
设计模式·程序员·架构