![e42d7098fee3e794f8dde54fad6dbe51.png](https://i-blog.csdnimg.cn/blog_migrate/ce6624b5ff66395873707c826e84e3aa.jpeg)
1.牢记动态代理的特点
- 在java中动态代理只能代理有接口的类(需要写个接口,并实现接口),不能使用抽象
- 使用 Proxy.newProxyInstance 实现
2.编写动态代理
1、创建代理类的接口类 HelloPrint
public interface HelloPrint { void printStr(String str1,String str2);}
2、编写HelloPrint实现HelloPrintImpl
public class HelloPrintImpl implements HelloPrint { @Override public void printStr(String str1,String str2){ System.out.println("Hello "+str1+" , "+str2); }}
3、编写main测试
/** * java 动态打理 * */public class HelloProxy { public static void main(String [] args){ HelloPrintImpl helloPrint1=new HelloPrintImpl(); HelloPrint helloPrint=(HelloPrint)Proxy.newProxyInstance(helloPrint1.getClass().getClassLoader(), helloPrint1.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.invoke(helloPrint1,args); } }); helloPrint.printStr("fishpro