Popular Posts
Add file to google drive using Google.Apis.Auth.OAuth2; using Google.Apis.Drive.v2; using Google.Apis.Drive.v2.Data; using Google.Apis.Services; using Google.Apis.Ut... Enable SSL connection for Jsoup import org.jsoup.Connection; import org.jsoup.Jsoup; import javax.net.ssl.*; import java.io.IOException; import java.security.KeyManagement... JavaMail sample import java.io.File; import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.Properties; import javax.activati...
Blog Archive
Stats
Dynamic Proxy
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Date;

public class MathObj implements IMath {

    @Override
    public double sum(Number... value) {
        double sum = 0;
        for (int i = 0; i < value.length; i++) {
            System.out.print(value[i]);
            if (i < value.length - 1)
                System.out.print(" + ");
            sum += value[i].doubleValue();
        }
        System.out.printf(" = %f%n", sum);
        return sum;
    }

    public static void main(String[] args) throws ClassNotFoundException {
        // 建立代理物件
        Object deleagate = Proxy.newProxyInstance(
                ObjectHandler.class.getClassLoader(),
                new Class[] { IMath.class },
                new ObjectHandler(new MathObj())
        );

        // 利用代理執行
        double sum = ((IMath) deleagate).sum(1, 2, 3, 4, 5, 6, 7);

        System.out.printf("Invoke result: %f%n", sum);
    }

}

// 定義代理程式
class ObjectHandler implements InvocationHandler {

    // 原始物件
    Object o;

    public ObjectHandler(Object o) {
        this.o = o;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 委派代理呼叫方法時, 要處理的動作
        System.out.println("Start at " + new Date());
        Object result = method.invoke(o, args);
        System.out.println("End at " + new Date());
        return result;
    }

}

// 定義介面
interface IMath {
    double sum(Number... value);
}
感想: 不好用xd