Javareflect-proxy-newproxyinstance
提供:Dev Guides
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配列の引数またはその要素のいずれかがnullの場合、または呼び出しハンドラhがnullの場合。
例
次の例は、java.lang.reflect.Proxy.newProxyInstance(ClassLoader loader、Class <?> [] interfaces、InvocationHandler h)メソッドの使用方法を示しています。
package com.finddevguides;
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 finddevguides");
return null;
}
}
interface SampleInterface {
void showMessage();
}
class SampleClass implements SampleInterface {
public void showMessage(){
System.out.println("Hello World");
}
}
上記のプログラムをコンパイルして実行すると、次の結果が生成されます-
com.finddevguides.SampleInvocationHandler