Java Code Examples for java.lang.reflect.Proxy#newProxyInstance()

The following examples show how to use java.lang.reflect.Proxy#newProxyInstance() . 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: RequestOnCompWithNullParent1.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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 2
Source File: AllocationStackTrace.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Imitates class loading. Each invocation of this method causes a new class
 * loader object is created and a new class is loaded by this class loader.
 * Method throws OOM when run out of memory.
 */
static protected void loadNewClass() {
    try {
        String jarUrl = "file:" + (counter++) + ".jar";
        URL[] urls = new URL[]{new URL(jarUrl)};
        URLClassLoader cl = new URLClassLoader(urls);
        Proxy.newProxyInstance(
                cl,
                new Class[]{Foo.class},
                new FooInvocationHandler(new FooBar()));
    } catch (java.net.MalformedURLException badThing) {
        // should never occur
        System.err.println("Unexpected error: " + badThing);
        throw new RuntimeException(badThing);
    }
}
 
Example 3
Source File: Boxing.java    From native-obfuscator with GNU General Public License v3.0 6 votes vote down vote up
private void run() {
    Random random = new Random(42); // ensure consistent test domain

    Test proxy = (Test) Proxy.newProxyInstance(
        Test.class.getClassLoader(),
        new Class<?>[] { Test.class },
        new TestHandler());

    for (int rep = 0; rep < REPS; rep++) {
        b = (byte) random.nextInt();
        c = (char) random.nextInt();
        d = random.nextDouble();
        f = random.nextFloat();
        i = random.nextInt();
        j = random.nextLong();
        s = (short) random.nextInt();
        z = random.nextBoolean();
        proxy.m(b,c,d,f,i,j,s,z);
    }
}
 
Example 4
Source File: FullscreenEnterEventTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void enableFullScreen(Window window) {
    try {
        Class fullScreenUtilities = Class.forName("com.apple.eawt.FullScreenUtilities");
        Method setWindowCanFullScreen = fullScreenUtilities.getMethod("setWindowCanFullScreen", Window.class, boolean.class);
        setWindowCanFullScreen.invoke(fullScreenUtilities, window, true);
        Class fullScreenListener = Class.forName("com.apple.eawt.FullScreenListener");
        Object listenerObject = Proxy.newProxyInstance(fullScreenListener.getClassLoader(), new Class[]{fullScreenListener}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                switch (method.getName()) {
                    case "windowEnteringFullScreen":
                        windowEnteringFullScreen = true;
                        break;
                    case "windowEnteredFullScreen":
                        windowEnteredFullScreen = true;
                        break;
                }
                return null;
            }
        });
        Method addFullScreenListener = fullScreenUtilities.getMethod("addFullScreenListenerTo", Window.class, fullScreenListener);
        addFullScreenListener.invoke(fullScreenUtilities, window, listenerObject);
    } catch (Exception e) {
        throw new RuntimeException("FullScreen utilities not available", e);
    }
}
 
Example 5
Source File: ProxyFactoryBean.java    From code with Apache License 2.0 5 votes vote down vote up
public Object getProxy(final Object target, final Advice advice) {

        Object proxyClass = Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                new InvocationHandler() {
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        advice.beforeMethod(method);
                        Object obj = method.invoke(target, args);
                        advice.afterMethod(method);
                        return obj;
                    }
                });
        return proxyClass;
    }
 
Example 6
Source File: FunctionExpression.java    From Quicksql with MIT License 5 votes vote down vote up
public F getFunction() {
  if (function != null) {
    return function;
  }
  if (dynamicFunction == null) {
    final Invokable x = compile();

    //noinspection unchecked
    dynamicFunction = (F) Proxy.newProxyInstance(getClass().getClassLoader(),
        new Class[]{Types.toClass(type)}, (proxy, method, args) -> x.dynamicInvoke(args));
  }
  return dynamicFunction;
}
 
Example 7
Source File: MBSFPreStartPostStartTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static MBeanServerForwarder newProxyInstance() {

            final InvocationHandler handler = new MBSFInvocationHandler();

            final Class[] interfaces =
                new Class[] {MBeanServerForwarder.class};

            Object proxy = Proxy.newProxyInstance(
                                 MBeanServerForwarder.class.getClassLoader(),
                                 interfaces,
                                 handler);

            return MBeanServerForwarder.class.cast(proxy);
        }
 
Example 8
Source File: MBeanServerForwarderInvocationHandler.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
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 9
Source File: ErrorFactory.java    From alibaba-flink-connectors with Apache License 2.0 5 votes vote down vote up
/**
 * create proxy instance for one module's error code interface.
 *
 * @param clazz interface that has error code definitions for one module.
 * @return instance of the interface that can be used by developer for specifying error code
 * (for now, it is for dumping error code and its cause&action message)
 * when throwing exceptions
 */
public static Object createProxy(Class clazz) {

	return Proxy.newProxyInstance(
		clazz.getClassLoader(),
		clazz.isInterface() ? new Class[]{clazz} : clazz.getInterfaces(),
		(obj, method, args) -> {
			checkParam(method, args);
			return assemblyErrCodeString(method, args);
		});

}
 
Example 10
Source File: RpcClient.java    From codedesign with Apache License 2.0 5 votes vote down vote up
public <T> T refer(final Class<T> interfaceClass, final String host, final int port) throws Exception {

    if (interfaceClass == null)
      throw new IllegalArgumentException("Interface class == null");
    if (! interfaceClass.isInterface())
      throw new IllegalArgumentException("The " + interfaceClass.getName() + " must be interface class!");
    if (host == null || host.length() == 0)
      throw new IllegalArgumentException("Host == null!");
    if (port <= 0 || port > 65535)
      throw new IllegalArgumentException("Invalid port " + port);

    return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[] {interfaceClass}, new InvocationHandler() {
      public Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable {
        Socket socket = new Socket(host, port);
        try {
          ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
          try {
            output.writeUTF(method.getName());
            output.writeObject(method.getParameterTypes());
            output.writeObject(arguments);
            ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
            try {
              Object result = input.readObject();
              if (result instanceof Throwable) {
                throw (Throwable) result;
              }
              return result;
            } finally {
              input.close();
            }
          } finally {
            output.close();
          }
        } finally {
          socket.close();
        }
      }
    });
  }
 
Example 11
Source File: SingleConnectionDataSource.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Wrap the given Connection with a proxy that delegates every method call to it
 * but suppresses close calls.
 * @param target the original Connection to wrap
 * @return the wrapped Connection
 */
protected Connection getCloseSuppressingConnectionProxy(Connection target) {
	return (Connection) Proxy.newProxyInstance(
			ConnectionProxy.class.getClassLoader(),
			new Class<?>[] {ConnectionProxy.class},
			new CloseSuppressingInvocationHandler(target));
}
 
Example 12
Source File: RpcClient.java    From springboot-learn with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T create(Class<T> interfaceClass) {
    return (T) Proxy.newProxyInstance(
            interfaceClass.getClassLoader(),
            new Class<?>[]{interfaceClass},
            new ObjectProxy<T>(interfaceClass)
    );
}
 
Example 13
Source File: CachingConnectionFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Wrap the given Session with a proxy that delegates every method call to it
 * but adapts close calls. This is useful for allowing application code to
 * handle a special framework Session just like an ordinary Session.
 * @param target the original Session to wrap
 * @param sessionList the List of cached Sessions that the given Session belongs to
 * @return the wrapped Session
 */
protected Session getCachedSessionProxy(Session target, LinkedList<Session> sessionList) {
	List<Class<?>> classes = new ArrayList<>(3);
	classes.add(SessionProxy.class);
	if (target instanceof QueueSession) {
		classes.add(QueueSession.class);
	}
	if (target instanceof TopicSession) {
		classes.add(TopicSession.class);
	}
	return (Session) Proxy.newProxyInstance(SessionProxy.class.getClassLoader(),
			ClassUtils.toClassArray(classes), new CachedSessionInvocationHandler(target, sessionList));
}
 
Example 14
Source File: LDAPConnectionContext.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the proxy for LDAP context and wrap the context.
 * Calculate the time taken for creation
 *
 * @param environment        Used to get provider url and principal
 * @param connectionControls The wrapped context
 * @return ldap connection context
 * @throws NamingException
 */
private LdapContext getLdapContext(Hashtable<?, ?> environment, Control[] connectionControls)
        throws NamingException, UserStoreException {

    if (Boolean.parseBoolean(System.getProperty(CORRELATION_LOG_SYSTEM_PROPERTY))) {
        final Class[] proxyInterfaces = new Class[]{LdapContext.class};
        long start = System.currentTimeMillis();

        LdapContext context = initializeLdapContext(environment, connectionControls);

        Object proxy = Proxy.newProxyInstance(LDAPConnectionContext.class.getClassLoader(), proxyInterfaces,
                new LdapContextInvocationHandler(context));

        long delta = System.currentTimeMillis() - start;

        CorrelationLogDTO correlationLogDTO = new CorrelationLogDTO();
        correlationLogDTO.setStartTime(start);
        correlationLogDTO.setDelta(delta);
        correlationLogDTO.setEnvironment(environment);
        correlationLogDTO.setMethodName(CORRELATION_LOG_INITIALIZATION_METHOD_NAME);
        correlationLogDTO.setArgsLength(CORRELATION_LOG_INITIALIZATION_ARGS_LENGTH);
        correlationLogDTO.setArgs(CORRELATION_LOG_INITIALIZATION_ARGS);
        logDetails(correlationLogDTO);
        return (LdapContext) proxy;
    } else {
        return initializeLdapContext(environment, connectionControls);
    }
}
 
Example 15
Source File: SpelReproTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void varargsAgainstProxy_SPR16122() {
	SpelExpressionParser parser = new SpelExpressionParser();
	Expression expr = parser.parseExpression("process('a', 'b')");

	VarargsReceiver receiver = new VarargsReceiver();
	VarargsInterface proxy = (VarargsInterface) Proxy.newProxyInstance(
			getClass().getClassLoader(), new Class<?>[] {VarargsInterface.class},
			(proxy1, method, args) -> method.invoke(receiver, args));

	assertEquals("OK", expr.getValue(new StandardEvaluationContext(receiver)));
	assertEquals("OK", expr.getValue(new StandardEvaluationContext(proxy)));
}
 
Example 16
Source File: PersistenceInjectionTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testPublicExtendedPersistenceContextSetterWithSerialization() throws Exception {
	DummyInvocationHandler ih = new DummyInvocationHandler();
	Object mockEm = Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[] {EntityManager.class}, ih);
	given(mockEmf.createEntityManager()).willReturn((EntityManager) mockEm);

	GenericApplicationContext gac = new GenericApplicationContext();
	SimpleMapScope myScope = new SimpleMapScope();
	gac.getDefaultListableBeanFactory().registerScope("myScope", myScope);
	gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
	gac.registerBeanDefinition("annotationProcessor",
			new RootBeanDefinition(PersistenceAnnotationBeanPostProcessor.class));
	RootBeanDefinition bd = new RootBeanDefinition(DefaultPublicPersistenceContextSetter.class);
	bd.setScope("myScope");
	gac.registerBeanDefinition(DefaultPublicPersistenceContextSetter.class.getName(), bd);
	gac.refresh();

	DefaultPublicPersistenceContextSetter bean = (DefaultPublicPersistenceContextSetter) gac.getBean(
			DefaultPublicPersistenceContextSetter.class.getName());
	assertNotNull(bean.em);
	assertNotNull(SerializationTestUtils.serializeAndDeserialize(bean.em));

	SimpleMapScope serialized = (SimpleMapScope) SerializationTestUtils.serializeAndDeserialize(myScope);
	serialized.close();
	assertTrue(DummyInvocationHandler.closed);
	DummyInvocationHandler.closed = false;
}
 
Example 17
Source File: ReflectiveRelMetadataProvider.java    From Quicksql with MIT License 4 votes vote down vote up
private static RelMetadataProvider reflectiveSource(
    final MetadataHandler target, final ImmutableList<Method> methods) {
  final Space2 space = Space2.create(target, methods);

  // This needs to be a concurrent map since RelMetadataProvider are cached in static
  // fields, thus the map is subject to concurrent modifications later.
  // See map.put in com.qihoo.qsql.org.apache.calcite.rel.metadata.ReflectiveRelMetadataProvider.apply(
  // java.lang.Class<? extends com.qihoo.qsql.org.apache.calcite.rel.RelNode>)
  final ConcurrentMap<Class<RelNode>, UnboundMetadata> methodsMap = new ConcurrentHashMap<>();
  for (Class<RelNode> key : space.classes) {
    ImmutableNullableList.Builder<Method> builder =
        ImmutableNullableList.builder();
    for (final Method method : methods) {
      builder.add(space.find(key, method));
    }
    final List<Method> handlerMethods = builder.build();
    final UnboundMetadata function = (rel, mq) ->
        (Metadata) Proxy.newProxyInstance(
            space.metadataClass0.getClassLoader(),
            new Class[]{space.metadataClass0}, (proxy, method, args) -> {
              // Suppose we are an implementation of Selectivity
              // that wraps "filter", a LogicalFilter. Then we
              // implement
              //   Selectivity.selectivity(rex)
              // by calling method
              //   new SelectivityImpl().selectivity(filter, rex)
              if (method.equals(BuiltInMethod.METADATA_REL.method)) {
                return rel;
              }
              if (method.equals(BuiltInMethod.OBJECT_TO_STRING.method)) {
                return space.metadataClass0.getSimpleName() + "(" + rel + ")";
              }
              int i = methods.indexOf(method);
              if (i < 0) {
                throw new AssertionError("not handled: " + method
                    + " for " + rel);
              }
              final Method handlerMethod = handlerMethods.get(i);
              if (handlerMethod == null) {
                throw new AssertionError("not handled: " + method
                    + " for " + rel);
              }
              final Object[] args1;
              final List key1;
              if (args == null) {
                args1 = new Object[]{rel, mq};
                key1 = FlatLists.of(rel, method);
              } else {
                args1 = new Object[args.length + 2];
                args1[0] = rel;
                args1[1] = mq;
                System.arraycopy(args, 0, args1, 2, args.length);

                final Object[] args2 = args1.clone();
                args2[1] = method; // replace RelMetadataQuery with method
                for (int j = 0; j < args2.length; j++) {
                  if (args2[j] == null) {
                    args2[j] = NullSentinel.INSTANCE;
                  } else if (args2[j] instanceof RexNode) {
                    // Can't use RexNode.equals - it is not deep
                    args2[j] = args2[j].toString();
                  }
                }
                key1 = FlatLists.copyOf(args2);
              }
              if (mq.map.put(key1, NullSentinel.INSTANCE) != null) {
                throw CyclicMetadataException.INSTANCE;
              }
              try {
                return handlerMethod.invoke(target, args1);
              } catch (InvocationTargetException
                  | UndeclaredThrowableException e) {
                Util.throwIfUnchecked(e.getCause());
                throw new RuntimeException(e.getCause());
              } finally {
                mq.map.remove(key1);
              }
            });
    methodsMap.put(key, function);
  }
  return new ReflectiveRelMetadataProvider(methodsMap, space.metadataClass0,
      space.providerMap);
}
 
Example 18
Source File: SingleConnectionFactory.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * Wrap the given Connection with a proxy that delegates every method call to it
 * but suppresses close calls. This is useful for allowing application code to
 * handle a special framework Connection just like an ordinary Connection from a
 * CCI ConnectionFactory.
 * @param target the original Connection to wrap
 * @return the wrapped Connection
 */
protected Connection getCloseSuppressingConnectionProxy(Connection target) {
	return (Connection) Proxy.newProxyInstance(
			Connection.class.getClassLoader(),
			new Class<?>[] {Connection.class},
			new CloseSuppressingInvocationHandler(target));
}
 
Example 19
Source File: TransactionAwareDataSourceProxy.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * Wraps the given Connection with a proxy that delegates every method call to it
 * but delegates {@code close()} calls to DataSourceUtils.
 * @param targetDataSource the DataSource that the Connection came from
 * @return the wrapped Connection
 * @see java.sql.Connection#close()
 * @see DataSourceUtils#doReleaseConnection
 */
protected Connection getTransactionAwareConnectionProxy(DataSource targetDataSource) {
	return (Connection) Proxy.newProxyInstance(
			ConnectionProxy.class.getClassLoader(),
			new Class<?>[] {ConnectionProxy.class},
			new TransactionAwareInvocationHandler(targetDataSource));
}
 
Example 20
Source File: HessianProxyFactory.java    From jvm-sandbox-repeater with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a new proxy with the specified URL.  The returned object
 * is a proxy with the interface specified by api.
 *
 * <pre>
 * String url = "http://localhost:8080/ejb/hello");
 * HelloHome hello = (HelloHome) factory.create(HelloHome.class, url);
 * </pre>
 *
 * @param api the interface the proxy class needs to implement
 * @param url the URL where the client object is located.
 *
 * @return a proxy to the object with the specified interface.
 */
public Object create(Class<?> api, URL url, ClassLoader loader)
{
  if (api == null)
    throw new NullPointerException("api must not be null for HessianProxyFactory.create()");
  InvocationHandler handler = null;

  handler = new HessianProxy(url, this, api);

  return Proxy.newProxyInstance(loader,
                                new Class[] { api,
                                              HessianRemoteObject.class },
                                handler);
}