java.lang.reflect.Proxy.isProxyClass(Class<?> cl)
方法當且僅當使用getProxyClass
方法或newProxyInstance
方法將指定的類動態生成為代理類時,方法才返回true
。
聲明
以下是java.lang.reflect.Proxy.isProxyClass(Class<?> cl)
方法的聲明。
public static boolean isProxyClass(Class<?> cl)
參數
- cl - 用於測試的類。
返回值
- 如果類是代理類,則返回
true
,否則返回false
。
異常
- NullPointerException - 如果
cl
是一個null
值。
示例
以下示例顯示了java.lang.reflect.Proxy.isProxyClass(Class<?> cl)
方法的用法。
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 });
System.out.println(Proxy.isProxyClass(proxyClass));
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");
}
}
讓我們編譯並運行上面的程式,這將產生以下結果 -
true
Welcome To xuhuhu.com