第六章:反射+设计模式

一、反射

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

相关推荐
周努力.9 小时前
设计模式之中介者模式
设计模式·中介者模式
yangyang_z1 天前
【C++设计模式之Template Method Pattern】
设计模式
源远流长jerry1 天前
常用设计模式
设计模式
z26373056111 天前
六大设计模式--OCP(开闭原则):构建可扩展软件的基石
设计模式·开闭原则
01空间1 天前
设计模式简述(十八)享元模式
设计模式·享元模式
秋名RG1 天前
深入理解设计模式之原型模式(Prototype Pattern)
设计模式·原型模式
Li小李同学Li2 天前
设计模式【cpp实现版本】
单例模式·设计模式
周努力.2 天前
设计模式之状态模式
设计模式·状态模式
268572592 天前
Java 23种设计模式 - 行为型模式11种
java·开发语言·设计模式
摘星编程2 天前
并发设计模式实战系列(19):监视器(Monitor)
设计模式·并发编程