java.lang.reflect.Proxy.getInvocationHandler()方法範例

2019-10-16 22:47:28

java.lang.reflect.Proxy.getInvocationHandler(Object proxy)方法返回指定代理範例的呼叫處理程式。

宣告

以下是java.lang.reflect.Proxy.getInvocationHandler(Object proxy)方法的宣告。

public static InvocationHandler getInvocationHandler(Object proxy)
   throws IllegalArgumentException

引數

  • proxy - 代理範例返回的呼叫處理程式。

返回值

  • 代理範例的呼叫處理程式。

異常

  • IllegalArgumentException - 如果引數不是代理範例則丟擲此異常。

範例

以下範例顯示了java.lang.reflect.Proxy.getInvocationHandler(Object proxy)方法的用法。

package com.yiibai;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyDemo {
    public static void main(String[] args) throws IllegalArgumentException {
        InvocationHandler handler = new SampleInvocationHandler();
        SampleInterface proxy = (SampleInterface) Proxy.newProxyInstance(
                SampleInterface.class.getClassLoader(),
                new Class[] { SampleInterface.class }, handler);
        Class invocationHandler = Proxy.getInvocationHandler(proxy).getClass();

        System.out.println(invocationHandler.getName());
    }
}

class SampleInvocationHandler implements InvocationHandler {

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        System.out.println("Welcome To Tw511.com");
        return null;
    }
}

interface SampleInterface {
    void showMessage();
}

class SampleClass implements SampleInterface {
    public void showMessage() {
        System.out.println("Hello World");
    }
}

讓我們編譯並執行上面的程式,這將產生以下結果 -

com.yiibai.SampleInvocationHandler