package edu.hunnu.proxy;public class Car implements Moveable {
public void move(){
System.out.println("car is moving!");
}}
package edu.hunnu.proxy;import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;public class Mhandler implements InvocationHandler{
Object target;
public Mhandler(Object target){
this.target=target;
}
@Override
public Object invoke(Object proxy, Method m, Object[] args)
throws Throwable {
System.out.println("汽车启动了");
m.invoke(target,args);
return null;
}
}
package edu.hunnu.proxy;public interface Moveable {
public void move();
}
package edu.hunnu.proxy;import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;public class Test {
public static void main(String args[]){
InvocationHandler h=new Mhandler(new Car());
try{
Moveable m=(Moveable)Proxy.newProxyInstance(Moveable.class.getClassLoader(), Moveable.class.getInterfaces(), h);
m.move();
}catch(ClassCastException e){
e.printStackTrace();
}
}
}
public void move(){
System.out.println("car is moving!");
}}
package edu.hunnu.proxy;import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;public class Mhandler implements InvocationHandler{
Object target;
public Mhandler(Object target){
this.target=target;
}
@Override
public Object invoke(Object proxy, Method m, Object[] args)
throws Throwable {
System.out.println("汽车启动了");
m.invoke(target,args);
return null;
}
}
package edu.hunnu.proxy;public interface Moveable {
public void move();
}
package edu.hunnu.proxy;import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;public class Test {
public static void main(String args[]){
InvocationHandler h=new Mhandler(new Car());
try{
Moveable m=(Moveable)Proxy.newProxyInstance(Moveable.class.getClassLoader(), Moveable.class.getInterfaces(), h);
m.move();
}catch(ClassCastException e){
e.printStackTrace();
}
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货