一、Java反射机制概述
1.1 Java Reflection
Reflection(反射)是被视为动态语言的关键 ,反射机制允许程序在执行期借助于Reflection API 取得任何类的内部信息 ,并能直接操作任意对象的内部属性及方法 加载完类之后,在堆内存的方法区中就产生了一个Class类型的对象(一个类只有一个Class对象 ),这个对象就包含了完整的类的结构信息 可以通过这个对象看到类的结构,形象的称之为:反射
1.2 动态语言 vs 静态语言
动态语言 静态语言 通俗点说就是在运 行时代码可以根据某些条件改变自身结构;如:Object-C、C#、JavaScript、PHP、Python、Erlang 运行时结构不可变的语言就是静态语言;如:Java、C、C++
Java不是动态语言,但Java可以称之为“准动态语言”。即Java有一定的动态性,可以利用反射机制、字节码操作获得类似动态语言的特性
1.3 Java反射机制提供的功能
在运行时 判断任意一个对象所属的类在运行时 构造任意一个类的对象在运行时 判断任意一个类所具有的成员变量和方法在运行时 获取泛型信息在运行时 调用任意一个对象的成员变量和方法在运行时 处理注解生成动态代理
1.4 反射相关的主要API
java.lang.Class
:代表一个类java.lang.reflect.Method
:代表类的方法java.lang.reflect.Field
:代表类的成员变量java.lang.reflect.Constructor
:代表类的构造器… …
二、Class类、获取Class的实例⭐
2.1 理解Class类
程序经过javac.exe
命令以后,会生成一个或多个字节码文件(.class结尾) 使用java.exe
命令对某个字节码文件进行解释运行 ,相当于将某个字节码文件加载到内存中 加载到内存中的类为运行时类 ,此运行时类,作为Class的一个实例 ,即Class的实例对应着一个运行时类 加载到内存中的运行时类,会缓存一定的时间,在此时间之内,可以通过不同的方式来获取此运行时类 public final Class getClass()
:在Object类中定义的方法,此方法将被所有子类继承
2.2 获取Class实例
Class clazz1 = Person. class ;
System. out. println ( clazz1) ;
Person p1 = new Person ( ) ;
Class clazz2 = p1. getClass ( ) ;
System. out. println ( clazz2) ;
Class clazz3 = Class. forName ( "com.lsy.java.Person" ) ;
System. out. println ( clazz3) ;
System. out. println ( clazz1 == clazz2) ;
System. out. println ( clazz1 == clazz3) ;
ClassLoader classLoader = ReflectionTest. class . getClassLoader ( ) ;
Class clazz4 = classLoader. loadClass ( "com.atguigu.java.Person" ) ;
System. out. println ( clazz4) ;
System. out. println ( clazz1 == clazz4) ;
2.3 可以有Class对象的类型
class
:外部类,成员(成员内部类,静态内部类),局部内部类,匿名内部类interface
:接口[]
:数组enum
:枚举annotation
:注解@interfaceprimitive type
:基本数据类型void
Class c1 = Object. class ; Class c2 = Comparable. class ; Class c3 = String[ ] . class ; Class c4 = int [ ] [ ] . class ; Class c5 = ElementType. class ; Class c6 = Override. class ; Class c7 = int . class ;
Class c8 = void . class ;
Class c9 = Class. class ;
int [ ] a = new int [ 10 ] ; int [ ] b = new int [ 100 ] ; Class c10 = a. getClass ( ) ; Class c11 = b. getClass ( ) ;
System. out. println ( c10 == c11) ;
2.4 Class类常用方法
Method Description static Class forName(String name)
返回指定类名name 的Class 对象 Object newInstance()
}调用缺省构造函数,返回该Class对象的一个实例 getName()
返回此Class对象所表示的实体(类、接口、数组类、基本类型或void)名称 Class getSuperClass()
返回当前Class对象的父类的Class对象 Class [] getInterfaces()
获取当前Class对象的接口 ClassLoader getClassLoader()
返回该类的类加载器 Class getSuperclass()
返回表示此Class所表示的实体的超类的Class Constructor[] getConstructors()
返回一个包含某些Constructor对象的数组 Field[] getDeclaredFields()
返回Field对象的一个数组 Method getMethod(Stringname,Class … paramTypes)
返回一个Method对象,此对象的形参类型为paramType
三、类的加载、ClassLoader
3.1 类的加载
加载:将class文件字节码内容加载到内存中,并将这些静态数据转换成方法区的运行时 数据结构,然后生成一个代表这个类的java.lang.Class对象,作为方法区中类数据的访问 入口(即引用地址)。所有需要访问和使用类数据只能通过这个Class对象。这个加载的 过程需要类加载器参与。 链接:将Java类的二进制代码合并到JVM的运行状态之中的过程。
验证:确保加载的类信息符合JVM规范,例如:以cafe开头,没有安全方面的问题 准备:正式为类变量(static)分配内存并设置类变量默认初始值的阶段,这些内存 都将在方法区中进行分配。 解析:虚拟机常量池内的符号引用(常量名)替换为直接引用(地址)的过程。 初始化:
执行类构造器()方法的过程。类构造器()方法是由编译期自动收集类中 所有类变量的赋值动作和静态代码块中的语句合并产生的。(类构造器是构造类信 息的,不是构造该类对象的构造器)。 当初始化一个类的时候,如果发现其父类还没有进行初始化,则需要先触发其父类 的初始化。 虚拟机会保证 一个类的()方法在多线程环境中被正确加锁和同步。
3.2 类加载器
类加载的作用:将class文件字节码内容加载到内存中,并将这些静态数据转换成方 法区的运行时数据结构,然后在堆中生成一个代表这个类的java.lang.Class对象,作为 方法区中类数据的访问入口。 类缓存:标准的JavaSE类加载器可以按要求查找类,但一旦某个类被加载到类加载器 中,它将维持加载(缓存)一段时间。不过JVM垃圾回收机制可以回收这些Class对象。
3.3 ClassLoader
使用Classloader
加载src
目录下的配置文件
@Test
public void test2 ( ) throws Exception {
Properties pros = new Properties ( ) ;
FileInputStream fis1 = new FileInputStream ( "jdbc.properties" ) ;
FileInputStream fis2 = new FileInputStream ( "src\\jdbc1.properties" ) ;
pros. load ( fis1) ;
pros. load ( fis2) ;
ClassLoader classLoader = ReflectionTest. class . getClassLoader ( ) ;
InputStream is = classLoader. getResourceAsStream ( "jdbc1.properties" ) ;
pros. load ( is) ;
String user = pros. getProperty ( "user" ) ;
String password = pros. getProperty ( "password" ) ;
System. out. println ( "user = " + user + ",password = " + password) ;
}
四、应用一:创建运行时类的对象⭐【newInstance】
@Test
public void test1 ( ) throws IllegalAccessException, InstantiationException {
Class< Person> clazz = Person. class ;
Person obj = clazz. newInstance ( ) ;
System. out. println ( obj) ;
}
五、应用二:获取运行时类的完整结构
5.1 属性结构
public class FieldTest {
@Test
public void test1 ( ) {
Class< Person> clazz = Person. class ;
Field[ ] fields = clazz. getFields ( ) ;
for ( Field f : fields) {
System. out. println ( f) ;
}
System. out. println ( "*******************************************" ) ;
Field[ ] declaredFields = clazz. getDeclaredFields ( ) ;
for ( Field f : declaredFields) {
System. out. println ( f) ;
}
}
@Test
public void test2 ( ) {
Class< Person> clazz = Person. class ;
Field[ ] declaredFields = clazz. getDeclaredFields ( ) ;
for ( Field f : declaredFields) {
int modifiers = f. getModifiers ( ) ;
System. out. print ( Modifier. toString ( modifiers) + "\t" ) ;
Class< ? > type = f. getType ( ) ;
System. out. print ( type. getName ( ) + "\t" ) ;
String name = f. getName ( ) ;
System. out. println ( name) ;
System. out. println ( ) ;
}
}
}
5.2 方法结构
public class MethodTest {
@Test
public void test1 ( ) {
Class< Person> clazz = Person. class ;
Method[ ] methods = clazz. getMethods ( ) ;
for ( Method m : methods) {
System. out. println ( m) ;
}
System. out. println ( "*************************************************" ) ;
Method[ ] declaredMethods = clazz. getDeclaredMethods ( ) ;
for ( Method m : declaredMethods) {
System. out. println ( m) ;
}
}
@Test
public void test2 ( ) {
Class< Person> clazz = Person. class ;
Method[ ] declaredMethods = clazz. getDeclaredMethods ( ) ;
for ( Method m : declaredMethods) {
Annotation[ ] annotations = m. getAnnotations ( ) ;
for ( Annotation a : annotations) {
System. out. println ( a) ;
}
System. out. print ( Modifier. toString ( m. getModifiers ( ) ) + "\t" ) ;
System. out. print ( m. getReturnType ( ) . getName ( ) + "\t" ) ;
System. out. print ( m. getName ( ) + "(" ) ;
Class[ ] parameterTypes = m. getParameterTypes ( ) ;
if ( parameterTypes. length > 0 ) {
for ( int i = 0 ; i< parameterTypes. length; i++ ) {
if ( i == parameterTypes. length- 1 ) {
System. out. print ( parameterTypes[ i] . getName ( ) + " args_" + i) ;
break ;
}
System. out. print ( parameterTypes[ i] . getName ( ) + " args_" + i + "," ) ;
}
}
System. out. print ( ")" + "\t" ) ;
Class[ ] exceptionTypes = m. getExceptionTypes ( ) ;
if ( exceptionTypes. length > 0 ) {
System. out. print ( " throws " ) ;
for ( int i= 0 ; i< exceptionTypes. length; i++ ) {
if ( i == exceptionTypes. length- 1 ) {
System. out. println ( exceptionTypes[ i] . getName ( ) ) ;
break ;
}
System. out. println ( exceptionTypes[ i] . getName ( ) + "," ) ;
}
}
System. out. println ( ) ;
}
}
}
5.3 构造器、父类、泛型、接口、包、注解
public class OtherTest {
@Test
public void test1 ( ) {
Class< Person> clazz = Person. class ;
Constructor< ? > [ ] constructors = clazz. getConstructors ( ) ;
for ( Constructor c : constructors) {
System. out. println ( c) ;
}
System. out. println ( "**********************************" ) ;
Constructor< ? > [ ] declaredConstructors = clazz. getDeclaredConstructors ( ) ;
for ( Constructor c : declaredConstructors) {
System. out. println ( c) ;
}
}
@Test
public void test2 ( ) {
Class< Person> clazz = Person. class ;
Class< ? super Person> superclass = clazz. getSuperclass ( ) ;
System. out. println ( superclass) ;
}
@Test
public void test3 ( ) {
Class< Person> clazz = Person. class ;
Type genericSuperclass = clazz. getGenericSuperclass ( ) ;
System. out. println ( genericSuperclass) ;
}
@Test
public void test4 ( ) {
Class< Person> clazz = Person. class ;
Type genericSuperclass = clazz. getGenericSuperclass ( ) ;
ParameterizedType parameterizedType = ( ParameterizedType) genericSuperclass;
Type[ ] actualTypeArguments = parameterizedType. getActualTypeArguments ( ) ;
for ( Type t : actualTypeArguments) {
System. out. println ( t. getTypeName ( ) ) ;
}
}
@Test
public void test5 ( ) {
Class< Person> clazz = Person. class ;
Class< ? > [ ] interfaces = clazz. getInterfaces ( ) ;
for ( Class c : interfaces) {
System. out. println ( c) ;
}
System. out. println ( "*************************" ) ;
Class< ? > [ ] interfaces1 = clazz. getSuperclass ( ) . getInterfaces ( ) ;
for ( Class c : interfaces1) {
System. out. println ( c) ;
}
}
@Test
public void test6 ( ) {
Class< Person> clazz = Person. class ;
Package clazzPackage = clazz. getPackage ( ) ;
System. out. println ( clazzPackage) ;
}
@Test
public void test7 ( ) {
Class< Person> clazz = Person. class ;
Annotation[ ] annotations = clazz. getAnnotations ( ) ;
for ( Annotation a : annotations) {
System. out. println ( a) ;
}
}
}
六、应用三:调用运行时类的指定结构⭐
6.1 调用运行时类的指定属性
@Test
public void testField ( ) throws Exception {
Class< Person> clazz = Person. class ;
Person p = clazz. newInstance ( ) ;
Field name = clazz. getDeclaredField ( "name" ) ;
name. setAccessible ( true ) ;
name. set ( p, "Tom" ) ;
System. out. println ( name. get ( p) ) ;
}
6.2 调用运行时类的指定方法
@Test
public void testMethod ( ) throws Exception {
Class< Person> clazz = Person. class ;
Person p = clazz. newInstance ( ) ;
Method show = clazz. getDeclaredMethod ( "show" , String. class ) ;
show. setAccessible ( true ) ;
Object returnValue = show. invoke ( p, "CHN" ) ;
System. out. println ( returnValue) ;
System. out. println ( "************************************************************" ) ;
Method showDesc = clazz. getDeclaredMethod ( "showDesc" ) ;
showDesc. setAccessible ( true ) ;
Object returnValue1 = showDesc. invoke ( null) ;
System. out. println ( returnValue1) ;
}
6.3 调用运行时类的指定构造器(用的少)
@Test
public void testConstructor ( ) throws Exception {
Class< Person> clazz = Person. class ;
Constructor< Person> constructor = clazz. getDeclaredConstructor ( String. class ) ;
constructor. setAccessible ( true ) ;
Person person = constructor. newInstance ( "Tom" ) ;
System. out. println ( person) ;
}
七、应用四:动态代理
代理设计模式的原理: 使用一个代理将对象包装起来, 然后用该代理对象取代原始对象。任何对原始对象的调用都要通过代理。代理对象决定是否以及何时将方法调用转到原始对象上。动态代理: 是指客户通过代理类来调用其它对象的方法,并且是在程序运行时 根据需要动态创建目标类的代理对象。
动态代理相比于静态代理的优点: 抽象角色中(接口)声明的所有方法都被转移到调用处理器一个集中的方法中处理,这样可以更加灵活和统一的处理众多的方法,即可以通过一个代理类完成全部的代理功能。
7.1 静态代理举例
interface ClothFactory {
void produceCloth ( ) ;
}
class ProxyClothFactory implements ClothFactory {
private ClothFactory factory;
public ProxyClothFactory ( ClothFactory factory) {
this . factory = factory;
}
@Override
public void produceCloth ( ) {
System. out. println ( "代理工厂准备" ) ;
factory. produceCloth ( ) ;
System. out. println ( "代理工厂收尾" ) ;
}
}
class NikeClothFactory implements ClothFactory {
@Override
public void produceCloth ( ) {
System. out. println ( "NIKE生产一批运动服" ) ;
}
}
public class StaticProxyTest {
public static void main ( String[ ] args) {
NikeClothFactory nikeClothFactory = new NikeClothFactory ( ) ;
ProxyClothFactory proxyClothFactory = new ProxyClothFactory ( nikeClothFactory) ;
proxyClothFactory. produceCloth ( ) ;
}
}
7.2 动态代理举例
interface Human {
String getBelief ( ) ;
void eat ( String food) ;
}
class Superman implements Human {
@Override
public String getBelief ( ) {
return "共产主义万岁" ;
}
@Override
public void eat ( String food) {
System. out. println ( "爱吃" + food) ;
}
}
class ProxyFactory {
public static Object getProxyInstance ( Object obj) {
MyInvocationHandler myInvocationHandler = new MyInvocationHandler ( ) ;
myInvocationHandler. bind ( obj) ;
return Proxy. newProxyInstance ( obj. getClass ( ) . getClassLoader ( ) , obj. getClass ( ) . getInterfaces ( ) , myInvocationHandler) ;
}
}
class MyInvocationHandler implements InvocationHandler {
private Object obj;
public void bind ( Object obj) {
this . obj = obj;
}
@Override
public Object invoke ( Object proxy, Method method, Object[ ] args) throws Throwable {
Object returnValue = method. invoke ( obj, args) ;
return returnValue;
}
}
public class ProxyTest {
public static void main ( String[ ] args) {
Superman superman = new Superman ( ) ;
Human proxyInstance = ( Human) ProxyFactory. getProxyInstance ( superman) ;
System. out. println ( proxyInstance. getBelief ( ) ) ;
proxyInstance. eat ( "锅包肉" ) ;
System. out. println ( "***********************************************" ) ;
NikeClothFactory nikeClothFactory = new NikeClothFactory ( ) ;
ClothFactory proxyClothInstance = ( ClothFactory) ProxyFactory. getProxyInstance ( nikeClothFactory) ;
proxyClothInstance. produceCloth ( ) ;
}
}
7.3 动态代理与AOP(Aspect Orient Programming)