/*
* MyInterface.java
*
* Created on 2007年9月8日, 下午4:38
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package test4;
/**
*
* @author hadeslee
*/
public interface MyInterface {
public void sayHello(String s);
public void doSth();
}
/*
* Test1.java
*
* Created on 2007年9月8日, 下午4:31
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package test4;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author hadeslee
*/
public class Test1 implements MyInterface{
/** Creates a new instance of Test1 */
public Test1() {
}
public static void main(String[] args) throws Exception{
Test1 list=new Test1();
MyInterface my=(MyInterface)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
list.getClass().getInterfaces(),
new MyHandler<MyInterface>(list));
System.out.println("my.name="+my.getClass().getName());
my.doSth();
my.sayHello("千里冰封");
}
//接口中的方法
public void sayHello(String s) {
System.out.println("sayHello to:"+s);
}
//接口中的方法
public void doSth() {
System.out.println("doSth()");
}
//一个静态内部类,实现了InvocationHandler的接口,
//它也是一个关键的接口,所有代理后的行为都是在这里实现的
static class MyHandler<T> implements InvocationHandler{
private T t;
public MyHandler(T t){
this.t=t;
}
//实现方法调用
//可以自己加上自己的一些调用,此例中只是在加上了一个输出
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("我知道马上要被调用的方法是:"+method.getName());
return method.invoke(t,args);
}
}
}
//实现方法调用
//可以自己加上自己的一些调用,此例中只是在加上了一个输出
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("我知道马上要被调用的方法是:"+method.getName());
return method.invoke(t,args);
}