Primero defina una interfaz:
class interface Istar(){
void dance();
void sing();
}
Luego defina una clase para implementar esta interfaz:
class Stars implements Istar(){
private String name;
public Stars(String name){
this.name = name;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
//重写方法
public void dance(){
System.out.println(getName+"跳一支舞");
}
public void sing(){
System.out.pritln(getName+"唱一首歌");
}
}
En este momento, se necesita una clase proxy para realizar el proxy dinámico de la clase estrella, es decir, para definir una clase proxy
public class StarNewProxy implement InvocationHandle{
private Object object;
public StarNewProxy(Object o){
this.object = o;
}
public Boolean runBefore(Method method){
System.out.println("拦截到一个请求");
if(method.getName().equals("dance")){
System.out.println("明星受伤了,不能跳舞");
return false;
}else{
System.out.println(method.getName()+"跳了一支舞");
return true;
}
}
pulic void runAfter(Method method){
System.out,println(method.getName()+"代理类请求完毕");
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (!RunBefore(method)){
return null;
}else{
Object result = method.invoke(object, args);
RunAfter(method);
return result;
}
}
}
Implemente la interfaz InvocationHandler y reescriba el método invoke. Method.invoke es ejecutar este método. Además, puede definir algunas otras operaciones antes y después de este método, que es similar a la idea de AOP.
Luego implementamos una clase de prueba
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class Test {
public static void main(String[] args) {
Istart istars = new Stars("Frank");
InvocationHandler starsNewProxy = new StarsNewProxy(istars);
Istart prox = (Istart) Proxy.newProxyInstance(istars.getClass().getClassLoader(),istars.getClass().getInterfaces(),starsNewProxy);
prox.dance();
// prox.sing();
}
}