1.创建student接口
package com.xq.DynamicProgramming;
public interface student {
void study();
void play();
}
2.创建studentImpl实现类实现student接口
package com.xq.DynamicProgramming;
public class studentImpl implements student {
public void study() {
// TODO Auto-generated method stub
System.out.println("study..");
}
public void play() {
// TODO Auto-generated method stub
System.out.println("play..");
}
}
3.创建myInvocationHandler类实现InvocationHandler
package com.xq.DynamicProgramming;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class myInvocationHandler implements InvocationHandler {
public Object target;
public myInvocationHandler(Object target) {
// TODO Auto-generated constructor stub
this.target=target;
}
public Object getInstance(Object target) {
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
System.out.println("before..");
method.invoke(target, args);
System.out.println("after..");
return null;
}
}
4.创建测试类test测试功能
package com.xq.DynamicProgramming;
import java.lang.reflect.Proxy;
public class test {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
student stu=new studentImpl();
stu.study();
System.out.println("--------------------------");
student st=new studentImpl();
myInvocationHandler m=new myInvocationHandler(st);
student s=(student) m.getInstance(st);
s.study();
}
}
效果如下: