package com. proxy;
public interface Person {
void run ( ) ;
void eat ( ) ;
}
package com. proxy;
public class Student implements Person {
@Override
public void run ( ) {
for ( int i = 0 ; i < 5 ; i++ ) {
System. out. println ( "have run" + i + "rounds" ) ;
}
}
@Override
public void eat ( ) {
for ( int i = 0 ; i < 5 ; i++ ) {
System. out. println ( "have eaten" + i + "apples" ) ;
}
}
}
package com. proxy;
import java. lang. reflect. InvocationHandler;
import java. lang. reflect. Method;
import java. lang. reflect. Proxy;
public class TimerProxyUtil {
public static Object getProxyInstance ( Object target) {
ClassLoader classLoader = target. getClass ( ) . getClassLoader ( ) ;
Class< ? > [ ] interfaces = target. getClass ( ) . getInterfaces ( ) ;
InvocationHandler h = new InvocationHandler ( ) {
@Override
public Object invoke ( Object arg0, Method arg1, Object[ ] arg2) throws Throwable {
long start = System. currentTimeMillis ( ) ;
arg1. invoke ( target, arg2) ;
long end = System. currentTimeMillis ( ) ;
System. out. println ( end - start) ;
return null;
}
} ;
return Proxy. newProxyInstance ( classLoader, interfaces, h) ;
}
}
package com. proxy;
public class Test {
public static void main ( String[ ] args) {
Student stu = new Student ( ) ;
Person tp2 = ( Person) TimerProxyUtil. getProxyInstance ( stu) ;
tp2. eat ( ) ;
tp2. run ( ) ;
}
}