- java.lang.reflect 包类
- java.lang.reflect - 主页
- java.lang.reflect - AccessibleObject
- java.lang.reflect - Array
- java.lang.reflect - Constructor<T>
- java.lang.reflect - Field
- java.lang.reflect - Method
- java.lang.reflect - Modifier
- java.lang.reflect - Proxy
- java.lang.reflect 包附加内容
- java.lang.reflect - 接口
- java.lang.reflect - 异常
- java.lang.reflect - 错误
- java.lang.reflect 有用资源
- java.lang.reflect - 快速指南
- java.lang.reflect - 有用资源
- java.lang.reflect - 讨论
java.lang.reflect.Proxy.getProxyClass() 方法示例
描述
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 − 如果接口数组参数或其任何元素为空。
示例
以下示例展示了 java.lang.reflect.Proxy.getProxyClass(ClassLoader loader, Class<?>... interfaces) 方法的用法。
package com.tutorialspoint;
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 TutorialsPoint");
return null;
}
}
interface SampleInterface {
void showMessage();
}
class SampleClass implements SampleInterface {
public void showMessage(){
System.out.println("Hello World");
}
}
编译并运行上述程序,它将产生以下结果 −
Welcome to TutorialsPoint
java_reflect_proxy.htm
广告