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

2019-10-16 22:47:32

java.lang.reflect.Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)方法返回指定介面的代理類的範例,這些介面將呼叫方法呼叫到指定的呼叫處理程式。

宣告

以下是java.lang.reflect.Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)方法的宣告。

public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces,
   InvocationHandler h)
      throws IllegalArgumentException

引數

  • loader - 類載入器來定義代理類。
  • interfaces - 代理類實現的介面列表。
  • h - 排程處理程式排程方法呼叫。

返回值

  • 一個代理範例,它是具有由指定的類載入器定義並實現指定介面的代理類的指定呼叫處理程式的代理範例。

異常

  • IllegalArgumentException - 如果對可能傳遞給getProxyClass的引數有限制。
  • NullPointerException - 如果interfaces陣列引數或其任何元素為空,或者呼叫處理程式hnull

範例

以下範例顯示了java.lang.reflect.Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)方法的用法。

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