本篇内容主要讲解“java动态代理的简单使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“java动态代理的简单使用”吧!
//---------------接口package reflect_test;public interface Animals {public String scrime(String str); }//--------------类package reflect_test;public class Dog implements Animals { private int age =100; private String xstr="test..."; public int page = 100000;private Dog(String xstr) { this.xstr = xstr; } public Dog() { } public Dog(int age) { this.age = age; }@Overridepublic String scrime(String str) {return str;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}private int getAddAge() {return age+=10;}public void getXstr() {System.out.println(xstr);}}-------------代理类package reflect_test;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;import org.junit.Before;import org.junit.Test;public class ProxyTest {@Testpublic void testProxy() throws Exception {Class<?> clazz = Class.forName("reflect_test.Dog");Class<?>[] interfa = {Class.forName("reflect_test.Animals")};Animals am = (Animals)Proxy.newProxyInstance(clazz.getClassLoader(), interfa, new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {String str = (String)method.invoke(new Dog(), args);return str + "\n append by proxy !";}});System.out.println(am.scrime("normal scriming....."));}}
到此,相信大家对“java动态代理的简单使用”有了更深的了解,不妨来实际操作一番吧!这里是编程网网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!