第六章:反射+设计模式

一、反射

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

相关推荐
Zyy~38 分钟前
《设计模式》工厂方法模式
设计模式·工厂方法模式
ikkkkkkkl3 小时前
C++设计模式:面向对象设计原则
c++·设计模式·面向对象
whitepure7 小时前
万字详解Java中的面向对象(二)——设计模式
java·设计模式
稚辉君.MCA_P8_Java9 小时前
豆包 Java的23种设计模式
java·linux·jvm·设计模式·kubernetes
快乐的划水a20 小时前
组合模式及优化
c++·设计模式·组合模式
Zyy~21 小时前
《设计模式》装饰模式
java·设计模式
落霞的思绪1 天前
Java设计模式详细解读
java·开发语言·设计模式
是2的10次方啊1 天前
🚀 JDK设计模式大揭秘:23种模式藏在你每天在用的类里
设计模式
步行cgn1 天前
设计模式(Design Patterns)
设计模式
Zyy~1 天前
《设计模式》代理模式
设计模式·代理模式