java.lang.reflect.Proxy.getProxyClass(ClassLoader loader, Class<?>... interfaces)
方法將給定類加載器和介面數組的代理類的方法返回java.lang.Class
對象。 代理類將由指定的類加載器定義,並將實現所有提供的介面。 如果類加載器已經定義了介面相同置換的代理類,那麼將返回現有的代理類; 否則,這些介面的代理類將被動態生成並由類加載器定義。
聲明
以下是java.lang.reflect.Proxy.getProxyClass(ClassLoader loader, Class<?>... interfaces)
方法的聲明。
public static Class<?> getProxyClass(ClassLoader loader, Class<?>... interfaces)
throws IllegalArgumentException
參數
- loader - 類加載器來定義代理類。
- interfaces - 代理類實現的介面列表。
返回值
- 在指定的類加載器中定義並實現指定介面的代理類。
異常
- IllegalArgumentException - 如果對可能傳遞給
getProxyClass
的參數有限制。 - NullPointerException - 如果
interfaces
數組參數或其任何元素為null
。
示例
以下示例顯示了java.lang.reflect.Proxy.getProxyClass(ClassLoader loader, Class<?>... interfaces)
方法的用法。
package com.zaixian;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyDemo {
public static void main(String[] args) throws IllegalArgumentException,
InstantiationException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException, SecurityException {
InvocationHandler handler = new SampleInvocationHandler();
Class proxyClass = Proxy.getProxyClass(
SampleClass.class.getClassLoader(),
new Class[] { SampleInterface.class });
SampleInterface proxy = (SampleInterface) proxyClass.getConstructor(
new Class[] { InvocationHandler.class }).newInstance(
new Object[] { handler });
proxy.showMessage();
}
}
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");
}
}
讓我們編譯並運行上面的程式,這將產生以下結果 -
Welcome To xuhuhu.com