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

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.zaixian;

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 xuhuhu.com");
        return null;
    }
}

interface SampleInterface {
    void showMessage();
}

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

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

com.zaixian.SampleInvocationHandler

上一篇: java.lang.reflect.Proxy類 下一篇: java.lang.reflect.Modifier類