/*
* 动态创建代理类
*/
public static <T> T getProxy(Class<?> interfaceType,final Object target) throws Exception{
if(!interfaceType.isInterface()){
throw new Exception("接口类型不正确!");
}
@SuppressWarnings("unchecked")
T targerInstance=(T)Proxy.newProxyInstance(interfaceType.getClassLoader(), new Class[]{interfaceType}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("开始");
Object value=method.invoke(target, args);
System.out.println("结束");
return value;
}
});
return targerInstance;
}
调用实例:
IStudent stu=getProxy(Class.forName("proxy.yl.IStudent"),Class.forName("proxy.yl.Student").newInstance());
stu.setName("xxxxx");
System.out.println(stu.getName());