JDK动态代理
new对象的方式
//case 1: 直接new HelloWorldImpl helloWorldImpl = new HelloWorldImpl(); //case 2: 反射拿到类之后,通过newInstance() HelloWorldImpl.class.newInstance(); //case 3: //HelloWorldImpl.class.getName()获取HelloWorldImpl类的绝对路劲 //Class.forName(HelloWorldImpl.class.getName())获取Class //cls.newInstance()实例化 Class<?> cls = Class.forName(HelloWorldImpl.class.getName()); cls.newInstance();
反射
package com.spring.aop.proxy; public class Preson { Preson() { System.out.println("this is person Constructor"); } private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
package com.spring.aop.proxy; import java.lang.reflect.Method; public class MethodReflect { /** * 调用反射类中的方法 */ public static void main(String[] args) { try { //属性名称 String attrbute = "name"; Class<?> cls = Class.forName(Preson.class.getName()); Object obj = cls.newInstance(); //initcap(attrbute)返回"Name" //获取Preson类中setName实际方法 Method setMethod = cls.getMethod("set" + initcap(attrbute), String.class); //获取Preson类中getName方法 Method getMethod = cls.getMethod("get" + initcap(attrbute)); //invoke相当于 实例化的类调用.setName("") setMethod.invoke(obj, "liuqiangaa"); //相当于 例化的类调用.getName() System.out.println(getMethod.invoke(obj)); } catch (Exception e) { e.printStackTrace(); } } //将字符串的首字母变为大写字母 public static String initcap(String str) { return str.substring(0, 1).toUpperCase() + str.substring(1); } }
动态代//接口
public interface IHelloWorld { void sayHello(); } //接口实现类 @Slf4j public class HelloWorldImpl implements IHelloWorld { @Override public void sayHello() { log.info("hello---"); } } //代理类 public class HelloInvocationHandler implements InvocationHandler { private Object target; public Object proxyHello(Object target) { this.target = target; //返回target代理对象 return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { log.info("begin invoke");
// 具体制定方法 method.invoke(target, args); log.info("end invoke"); return target; } } //测试类 public static void main(String[] args) { HelloInvocationHandler helloInvocationHandler = new HelloInvocationHandler(); //获取到new HelloWorldImpl()代理对象 IHelloWorld helloWorld = (IHelloWorld) helloInvocationHandler.proxyHello(new HelloWorldImpl()); //代理对象执行的任何操作都会被代理类的invoke方法捕获,交给method.invoke(target, args);执行
helloWorld.sayHello(); }