java.lang.reflect.InvocationHandler Java Examples
The following examples show how to use
java.lang.reflect.InvocationHandler.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ProxyArrays.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
/** * 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; }
Example #2
Source File: AkkaRpcService.java From Flink-CEPplus with Apache License 2.0 | 6 votes |
@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."); } }
Example #3
Source File: ProxyUtil.java From jsonrpc4j with MIT License | 6 votes |
/** * 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); } }); }
Example #4
Source File: ProxyFragment.java From AndroidQuick with MIT License | 6 votes |
@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); }
Example #5
Source File: TestUtils.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
/** * 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; }
Example #6
Source File: RequestOnCompWithNullParent1.java From openjdk-8-source with GNU General Public License v2.0 | 6 votes |
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); }
Example #7
Source File: DubboMonitorConsumerFactory.java From EasyTransaction with Apache License 2.0 | 6 votes |
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); } }); }
Example #8
Source File: RequestOnCompWithNullParent1.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 6 votes |
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); }
Example #9
Source File: RequestOnCompWithNullParent1.java From jdk8u_jdk with GNU General Public License v2.0 | 6 votes |
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); }
Example #10
Source File: ProxyUtils.java From chrome-devtools-java-client with Apache License 2.0 | 6 votes |
/** * 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); } }
Example #11
Source File: TestUtils.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
/** * 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; }
Example #12
Source File: AnnotationProcessor.java From carbon-device-mgt with Apache License 2.0 | 6 votes |
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; }
Example #13
Source File: BizSocketRxSupport.java From bizsocket with Apache License 2.0 | 6 votes |
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); } }); }
Example #14
Source File: ProxyServiceFactory.java From container with GNU General Public License v3.0 | 6 votes |
@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; } } }; } }; }
Example #15
Source File: CrnkClient.java From crnk-framework with Apache License 2.0 | 6 votes |
@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); }
Example #16
Source File: NonPublicProxyClass.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
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; } } }
Example #17
Source File: ScriptEngineTest.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
@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]); }
Example #18
Source File: ApkBundleLauncher.java From Small with Apache License 2.0 | 5 votes |
@Override public void setUp(Context context) { super.setUp(context); Field f; // AOP for pending intent try { f = TaskStackBuilder.class.getDeclaredField("IMPL"); f.setAccessible(true); final Object impl = f.get(TaskStackBuilder.class); InvocationHandler aop = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Intent[] intents = (Intent[]) args[1]; for (Intent intent : intents) { sBundleInstrumentation.wrapIntent(intent); intent.setAction(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); } return method.invoke(impl, args); } }; Object newImpl = Proxy.newProxyInstance(context.getClassLoader(), impl.getClass().getInterfaces(), aop); f.set(TaskStackBuilder.class, newImpl); } catch (Exception ignored) { Log.e(TAG, "Failed to hook TaskStackBuilder. \n" + "Please manually call `Small.wrapIntent` to ensure the notification intent can be opened. \n" + "See https://github.com/wequick/Small/issues/547 for details."); } }
Example #19
Source File: ProxyArrayCalls.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
/** * 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; }
Example #20
Source File: MXBeanLookup.java From openjdk-8 with GNU General Public License v2.0 | 5 votes |
synchronized ObjectName mxbeanToObjectName(Object mxbean) throws OpenDataException { String wrong; if (mxbean instanceof Proxy) { InvocationHandler ih = Proxy.getInvocationHandler(mxbean); if (ih instanceof MBeanServerInvocationHandler) { MBeanServerInvocationHandler mbsih = (MBeanServerInvocationHandler) ih; if (mbsih.getMBeanServerConnection().equals(mbsc)) return mbsih.getObjectName(); else wrong = "proxy for a different MBeanServer"; } else wrong = "not a JMX proxy"; } else { ObjectName name = mxbeanToObjectName.get(mxbean); if (name != null) return name; wrong = "not an MXBean registered in this MBeanServer"; } String s = (mxbean == null) ? "null" : "object of type " + mxbean.getClass().getName(); throw new OpenDataException( "Could not convert " + s + " to an ObjectName: " + wrong); // Message will be strange if mxbean is null but it is not // supposed to be. }
Example #21
Source File: MBeanServerMXBeanUnsupportedTest.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
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); }
Example #22
Source File: DumpNodes.java From Markwon with Apache License 2.0 | 5 votes |
@NonNull public static String dump(@NonNull Node node, @Nullable NodeProcessor nodeProcessor) { final NodeProcessor processor = nodeProcessor != null ? nodeProcessor : new NodeProcessorToString(); final Indent indent = new Indent(); final StringBuilder builder = new StringBuilder(); final Visitor visitor = (Visitor) Proxy.newProxyInstance( Visitor.class.getClassLoader(), new Class[]{Visitor.class}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) { final Node argument = (Node) args[0]; // initial indent indent.appendTo(builder); // node info builder.append(processor.process(argument)); if (argument instanceof Block) { builder.append(" [\n"); indent.increment(); visitChildren((Visitor) proxy, argument); indent.decrement(); indent.appendTo(builder); builder.append("]\n"); } else { builder.append('\n'); } return null; } }); node.accept(visitor); return builder.toString(); }
Example #23
Source File: MBeanServerInvocationHandler.java From Java8CN with Apache License 2.0 | 5 votes |
private Object doLocally(Object proxy, Method method, Object[] args) { final String methodName = method.getName(); if (methodName.equals("equals")) { if (this == args[0]) { return true; } if (!(args[0] instanceof Proxy)) { return false; } final InvocationHandler ihandler = Proxy.getInvocationHandler(args[0]); if (ihandler == null || !(ihandler instanceof MBeanServerInvocationHandler)) { return false; } final MBeanServerInvocationHandler handler = (MBeanServerInvocationHandler)ihandler; return connection.equals(handler.connection) && objectName.equals(handler.objectName) && proxy.getClass().equals(args[0].getClass()); } else if (methodName.equals("toString")) { return (isMXBean() ? "MX" : "M") + "BeanProxy(" + connection + "[" + objectName + "])"; } else if (methodName.equals("hashCode")) { return objectName.hashCode()+connection.hashCode(); } else if (methodName.equals("finalize")) { // ignore the finalizer invocation via proxy return null; } throw new RuntimeException("Unexpected method name: " + methodName); }
Example #24
Source File: MBeanServerInvocationHandler.java From openjdk-8 with GNU General Public License v2.0 | 5 votes |
private Object doLocally(Object proxy, Method method, Object[] args) { final String methodName = method.getName(); if (methodName.equals("equals")) { if (this == args[0]) { return true; } if (!(args[0] instanceof Proxy)) { return false; } final InvocationHandler ihandler = Proxy.getInvocationHandler(args[0]); if (ihandler == null || !(ihandler instanceof MBeanServerInvocationHandler)) { return false; } final MBeanServerInvocationHandler handler = (MBeanServerInvocationHandler)ihandler; return connection.equals(handler.connection) && objectName.equals(handler.objectName) && proxy.getClass().equals(args[0].getClass()); } else if (methodName.equals("toString")) { return (isMXBean() ? "MX" : "M") + "BeanProxy(" + connection + "[" + objectName + "])"; } else if (methodName.equals("hashCode")) { return objectName.hashCode()+connection.hashCode(); } throw new RuntimeException("Unexpected method name: " + methodName); }
Example #25
Source File: MixinModel.java From attic-polygene-java with Apache License 2.0 | 5 votes |
protected FragmentInvocationHandler newInvocationHandler( Method method ) { if( InvocationHandler.class.isAssignableFrom( mixinClass ) && !method.getDeclaringClass().isAssignableFrom( mixinClass ) ) { return new GenericFragmentInvocationHandler(); } else { return new TypedModifierInvocationHandler(); } }
Example #26
Source File: WSServiceDelegate.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
private <T> T createProxy(final Class<T> portInterface, final InvocationHandler pis) { // When creating the proxy, use a ClassLoader that can load classes // from both the interface class and also from this classes // classloader. This is necessary when this code is used in systems // such as OSGi where the class loader for the interface class may // not be able to load internal JAX-WS classes like // "WSBindingProvider", but the class loader for this class may not // be able to load the interface class. final ClassLoader loader = getDelegatingLoader(portInterface.getClassLoader(), WSServiceDelegate.class.getClassLoader()); // accessClassInPackage privilege needs to be granted ... RuntimePermission perm = new RuntimePermission("accessClassInPackage.com.sun." + "xml.internal.*"); PermissionCollection perms = perm.newPermissionCollection(); perms.add(perm); return AccessController.doPrivileged( new PrivilegedAction<T>() { @Override public T run() { Object proxy = Proxy.newProxyInstance(loader, new Class[]{portInterface, WSBindingProvider.class, Closeable.class}, pis); return portInterface.cast(proxy); } }, new AccessControlContext( new ProtectionDomain[]{ new ProtectionDomain(null, perms) }) ); }
Example #27
Source File: Types.java From moshi with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") static <T extends Annotation> T createJsonQualifierImplementation(final Class<T> annotationType) { if (!annotationType.isAnnotation()) { throw new IllegalArgumentException(annotationType + " must be an annotation."); } if (!annotationType.isAnnotationPresent(JsonQualifier.class)) { throw new IllegalArgumentException(annotationType + " must have @JsonQualifier."); } if (annotationType.getDeclaredMethods().length != 0) { throw new IllegalArgumentException(annotationType + " must not declare methods."); } return (T) Proxy.newProxyInstance(annotationType.getClassLoader(), new Class<?>[] { annotationType }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); switch (methodName) { case "annotationType": return annotationType; case "equals": Object o = args[0]; return annotationType.isInstance(o); case "hashCode": return 0; case "toString": return "@" + annotationType.getName() + "()"; default: return method.invoke(proxy, args); } } }); }
Example #28
Source File: KatharsisClient.java From katharsis-framework with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") public <R extends ResourceRepositoryV2<?, ?>> R getRepositoryForInterface(Class<R> repositoryInterfaceClass) { RepositoryInformationBuilder informationBuilder = moduleRegistry.getRepositoryInformationBuilder(); PreconditionUtil.assertTrue("no a valid repository interface", informationBuilder.accept(repositoryInterfaceClass)); ResourceRepositoryInformation repositoryInformation = (ResourceRepositoryInformation) informationBuilder.build(repositoryInterfaceClass, newRepositoryInformationBuilderContext()); Class<?> resourceClass = repositoryInformation.getResourceInformation().getResourceClass(); Object actionStub = actionStubFactory != null ? actionStubFactory.createStub(repositoryInterfaceClass) : null; ResourceRepositoryV2<?, Serializable> repositoryStub = getQuerySpecRepository(resourceClass); ClassLoader classLoader = repositoryInterfaceClass.getClassLoader(); InvocationHandler invocationHandler = new ClientStubInvocationHandler(repositoryInterfaceClass, repositoryStub, actionStub); return (R) Proxy.newProxyInstance(classLoader, new Class[] { repositoryInterfaceClass, ResourceRepositoryV2.class }, invocationHandler); }
Example #29
Source File: ScriptEngineSecurityTest.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
@Test public static void proxyStaticAccessCheckTest() { if (System.getSecurityManager() == null) { // pass vacuously return; } final ScriptEngineManager m = new ScriptEngineManager(); final ScriptEngine e = m.getEngineByName("nashorn"); 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) { return null; } }); e.put("rc", r.getClass()); e.put("cl", ScriptEngineSecurityTest.class.getClassLoader()); e.put("intfs", new Class[] { Runnable.class }); // make sure static methods of Proxy is not accessible via subclass try { e.eval("rc.static.getProxyClass(cl, intfs)"); fail("Should have thrown SecurityException"); } catch (final Exception exp) { if (! (exp instanceof SecurityException)) { fail("SecurityException expected, got " + exp); } } }
Example #30
Source File: SimpleTimeLimiter.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
@Override public <T> T newProxy( final T target, Class<T> interfaceType, final long timeoutDuration, final TimeUnit timeoutUnit) { checkNotNull(target); checkNotNull(interfaceType); checkNotNull(timeoutUnit); checkArgument(timeoutDuration > 0, "bad timeout: %s", timeoutDuration); checkArgument(interfaceType.isInterface(), "interfaceType must be an interface type"); final Set<Method> interruptibleMethods = findInterruptibleMethods(interfaceType); InvocationHandler handler = new InvocationHandler() { @Override public Object invoke(Object obj, final Method method, final Object[] args) throws Throwable { Callable<Object> callable = new Callable<Object>() { @Override public Object call() throws Exception { try { return method.invoke(target, args); } catch (InvocationTargetException e) { throw throwCause(e, false); } } }; return callWithTimeout(callable, timeoutDuration, timeoutUnit, interruptibleMethods.contains(method)); } }; return newProxy(interfaceType, handler); }