java.lang.reflect.Proxy#newProxyInstance ( )源码实例Demo

下面列出了java.lang.reflect.Proxy#newProxyInstance ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: native-obfuscator   文件: Boxing.java
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);
    }
}
 
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);
    }
}
 
源代码3 项目: dragonwell8_jdk   文件: AllocationStackTrace.java
/**
 * 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);
    }
}
 
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);
}
 
源代码5 项目: code   文件: ProxyFactoryBean.java
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;
    }
 
@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;
}
 
源代码7 项目: java-technology-stack   文件: SpelReproTests.java
@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)));
}
 
源代码8 项目: micro-integrator   文件: LDAPConnectionContext.java
/**
 * 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);
    }
}
 
/**
 * 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));
}
 
源代码10 项目: springboot-learn   文件: RpcClient.java
@SuppressWarnings("unchecked")
public static <T> T create(Class<T> interfaceClass) {
    return (T) Proxy.newProxyInstance(
            interfaceClass.getClassLoader(),
            new Class<?>[]{interfaceClass},
            new ObjectProxy<T>(interfaceClass)
    );
}
 
/**
 * 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));
}
 
源代码12 项目: codedesign   文件: RpcClient.java
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();
        }
      }
    });
  }
 
源代码13 项目: alibaba-flink-connectors   文件: ErrorFactory.java
/**
 * 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);
		});

}
 
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);
    }
 
源代码15 项目: TencentKona-8   文件: MBSFPreStartPostStartTest.java
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);
        }
 
源代码16 项目: Quicksql   文件: FunctionExpression.java
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;
}
 
源代码17 项目: Quicksql   文件: ReflectiveRelMetadataProvider.java
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);
}
 
源代码18 项目: jvm-sandbox-repeater   文件: HessianProxyFactory.java
/**
 * 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);
}
 
/**
 * 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));
}
 
/**
 * 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));
}