进阶day13-静态代理实现
This commit is contained in:
41
javaSE-day13/src/com/inmind/proxy01/Demo03.java
Normal file
41
javaSE-day13/src/com/inmind/proxy01/Demo03.java
Normal file
@@ -0,0 +1,41 @@
|
||||
package com.inmind.proxy01;
|
||||
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Proxy;
|
||||
|
||||
/*
|
||||
静态代理:直接定义一个固定的类,增强某个类的功能(JingJiRen)
|
||||
动态代理:不用定义一个固定的类,动态地增强某个类的功能
|
||||
|
||||
需求:蔡徐坤的类不能改变,也不能定义经纪人类,但是还想对蔡徐坤的唱跳功能,增强金额判断
|
||||
此时只能使用动态代理.
|
||||
*/
|
||||
public class Demo03 {
|
||||
public static void main(String[] args) {
|
||||
//创建出被代理的类-蔡徐坤
|
||||
CaiXuKun caiXuKun = new CaiXuKun();
|
||||
|
||||
|
||||
//动态代理参数一:类加载器
|
||||
ClassLoader classLoader = caiXuKun.getClass().getClassLoader();
|
||||
//动态代理参数二:代理对象要与被代理对象拥有相同的功能,(实现同一套接口)
|
||||
Class<?>[] interfaces = caiXuKun.getClass().getInterfaces();
|
||||
//动态代理参数三:处理器对象,用来处理代理对象的业务逻辑
|
||||
InvocationHandler handler = new InvocationHandler() {
|
||||
/*
|
||||
注意:动态代理对象singerProxy调用任意方法功能,都会引起处理器的invoke方法来执行
|
||||
*/
|
||||
@Override
|
||||
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
|
||||
System.out.println("处理器的invoke方法执行了");
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
//动态地创建出一个代理对象(类似一个经纪人)
|
||||
Singer singerProxy = (Singer) Proxy.newProxyInstance(classLoader, interfaces, handler);//多态
|
||||
singerProxy.dance(10);
|
||||
singerProxy.sing(10);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user