public interface Car {
void run ( int speed) ;
}
public class PoliceCar implements Car {
@Override
public void run ( int speed) {
System . out. println ( "警车速度" + speed+ ",奔跑!" ) ;
}
}
package itcast. proxyTest ;
import java. lang. reflect. InvocationHandler ;
import java. lang. reflect. Method ;
public class ObjInvocationHandler < T > implements InvocationHandler {
T obj;
public ObjInvocationHandler ( T obj) {
this . obj= obj;
}
@Override
public Object invoke ( Object proxy, Method method, Object [ ] args) throws Throwable {
System . out. println ( "方法执行前的操作" ) ;
Object res = method. invoke ( obj, args) ;
System . out. println ( "方法执行后的操作" ) ;
return res;
}
}
public class testMain {
@Test
public void test1 ( ) {
PoliceCar pcar = new PoliceCar ( ) ;
ObjInvocationHandler < Car > carHandler = new ObjInvocationHandler < > ( pcar) ;
Car cc = ( Car ) Proxy . newProxyInstance ( PoliceCar . class . getClassLoader ( ) , PoliceCar . class . getInterfaces ( ) , carHandler) ;
cc. run ( 220 ) ;
}
}