java.lang.reflect.Proxy Java Examples

The following examples show how to use java.lang.reflect.Proxy. 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: SerialFilterTest.java    From TencentKona-8 with GNU General Public License v2.0 7 votes vote down vote up
@Override
public ObjectInputFilter.Status checkInput(FilterInfo filter) {
    Class<?> serialClass = filter.serialClass();
    System.out.printf("     checkInput: class: %s, arrayLen: %d, refs: %d, depth: %d, bytes; %d%n",
            serialClass, filter.arrayLength(), filter.references(),
            filter.depth(), filter.streamBytes());
    count++;
    if (serialClass != null) {
        if (serialClass.getName().contains("$$Lambda$")) {
            // TBD: proper identification of serialized Lambdas?
            // Fold the serialized Lambda into the SerializedLambda type
            classes.add(SerializedLambda.class);
        } else if (Proxy.isProxyClass(serialClass)) {
            classes.add(Proxy.class);
        } else {
            classes.add(serialClass);
        }

    }
    this.maxArray = Math.max(this.maxArray, filter.arrayLength());
    this.maxRefs = Math.max(this.maxRefs, filter.references());
    this.maxDepth = Math.max(this.maxDepth, filter.depth());
    this.maxBytes = Math.max(this.maxBytes, filter.streamBytes());
    return ObjectInputFilter.Status.UNDECIDED;
}
 
Example #2
Source File: DefaultAopProxyFactory.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
	// 创建代理,这里有两种代理类型 1. JDK 动态代理 2. CGLIB 动态代理
	if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
		Class<?> targetClass = config.getTargetClass();
		if (targetClass == null) {
			throw new AopConfigException("TargetSource cannot determine target class: " +
					"Either an interface or a target is required for proxy creation.");
		}
		if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
			return new JdkDynamicAopProxy(config);
		}
		return new ObjenesisCglibAopProxy(config);
	}
	else {
		return new JdkDynamicAopProxy(config);
	}
}
 
Example #3
Source File: AnnotationUtils.java    From java-technology-stack with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
static <A extends Annotation> A synthesizeAnnotation(A annotation, @Nullable Object annotatedElement) {
	if (annotation instanceof SynthesizedAnnotation || hasPlainJavaAnnotationsOnly(annotatedElement)) {
		return annotation;
	}

	Class<? extends Annotation> annotationType = annotation.annotationType();
	if (!isSynthesizable(annotationType)) {
		return annotation;
	}

	DefaultAnnotationAttributeExtractor attributeExtractor =
			new DefaultAnnotationAttributeExtractor(annotation, annotatedElement);
	InvocationHandler handler = new SynthesizedAnnotationInvocationHandler(attributeExtractor);

	// Can always expose Spring's SynthesizedAnnotation marker since we explicitly check for a
	// synthesizable annotation before (which needs to declare @AliasFor from the same package)
	Class<?>[] exposedInterfaces = new Class<?>[] {annotationType, SynthesizedAnnotation.class};
	return (A) Proxy.newProxyInstance(annotation.getClass().getClassLoader(), exposedInterfaces, handler);
}
 
Example #4
Source File: ContainerManagedEntityManagerIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testEntityManagerProxyIsProxy() {
	EntityManager em = createContainerManagedEntityManager();
	assertTrue(Proxy.isProxyClass(em.getClass()));
	Query q = em.createQuery("select p from Person as p");
	List<Person> people = q.getResultList();
	assertTrue(people.isEmpty());

	assertTrue("Should be open to start with", em.isOpen());
	try {
		em.close();
		fail("Close should not work on container managed EM");
	}
	catch (IllegalStateException ex) {
		// OK
	}
	assertTrue(em.isOpen());
}
 
Example #5
Source File: ObjectStreamClass.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns ObjectStreamField array describing the serializable fields of
 * the given class.  Serializable fields backed by an actual field of the
 * class are represented by ObjectStreamFields with corresponding non-null
 * Field objects.  Throws InvalidClassException if the (explicitly
 * declared) serializable fields are invalid.
 */
private static ObjectStreamField[] getSerialFields(Class<?> cl)
    throws InvalidClassException
{
    ObjectStreamField[] fields;
    if (Serializable.class.isAssignableFrom(cl) &&
        !Externalizable.class.isAssignableFrom(cl) &&
        !Proxy.isProxyClass(cl) &&
        !cl.isInterface())
    {
        if ((fields = getDeclaredSerialFields(cl)) == null) {
            fields = getDefaultSerialFields(cl);
        }
        Arrays.sort(fields);
    } else {
        fields = NO_FIELDS;
    }
    return fields;
}
 
Example #6
Source File: ContainerManagedEntityManagerIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testEntityManagerProxyIsProxy() {
	EntityManager em = createContainerManagedEntityManager();
	assertTrue(Proxy.isProxyClass(em.getClass()));
	Query q = em.createQuery("select p from Person as p");
	List<Person> people = q.getResultList();
	assertTrue(people.isEmpty());

	assertTrue("Should be open to start with", em.isOpen());
	try {
		em.close();
		fail("Close should not work on container managed EM");
	}
	catch (IllegalStateException ex) {
		// OK
	}
	assertTrue(em.isOpen());
}
 
Example #7
Source File: ExtendedEntityManagerCreator.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Actually create the EntityManager proxy.
 * @param rawEm raw EntityManager
 * @param emIfc the (potentially vendor-specific) EntityManager
 * interface to proxy, or {@code null} for default detection of all interfaces
 * @param cl the ClassLoader to use for proxy creation (maybe {@code null})
 * @param exceptionTranslator the PersistenceException translator to use
 * @param jta whether to create a JTA-aware EntityManager
 * (or {@code null} if not known in advance)
 * @param containerManaged whether to follow container-managed EntityManager
 * or application-managed EntityManager semantics
 * @param synchronizedWithTransaction whether to automatically join ongoing
 * transactions (according to the JPA 2.1 SynchronizationType rules)
 * @return the EntityManager proxy
 */
private static EntityManager createProxy(
		EntityManager rawEm, @Nullable Class<? extends EntityManager> emIfc, @Nullable ClassLoader cl,
		@Nullable PersistenceExceptionTranslator exceptionTranslator, @Nullable Boolean jta,
		boolean containerManaged, boolean synchronizedWithTransaction) {

	Assert.notNull(rawEm, "EntityManager must not be null");
	Set<Class<?>> ifcs = new LinkedHashSet<>();
	if (emIfc != null) {
		ifcs.add(emIfc);
	}
	else {
		ifcs.addAll(ClassUtils.getAllInterfacesForClassAsSet(rawEm.getClass(), cl));
	}
	ifcs.add(EntityManagerProxy.class);
	return (EntityManager) Proxy.newProxyInstance(
			(cl != null ? cl : ExtendedEntityManagerCreator.class.getClassLoader()),
			ClassUtils.toClassArray(ifcs),
			new ExtendedEntityManagerInvocationHandler(
					rawEm, exceptionTranslator, jta, containerManaged, synchronizedWithTransaction));
}
 
Example #8
Source File: ProxyArrays.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #9
Source File: KernelProxyBuilder.java    From openAGV with Apache License 2.0 6 votes vote down vote up
/**
 * Builds and returns a {@link KernelProxy} with the configured parameters.
 *
 * @return A proxy for the remote kernel.
 * @throws KernelUnavailableException If the remote kernel is not reachable for some reason.
 * @throws CredentialsException If the client login with the remote kernel failed, e.g. because of
 * incorrect login data.
 * @see RemoteKernel#pollEvents(ClientID, long)
 */
@SuppressWarnings("deprecation")
public KernelProxy build()
    throws KernelUnavailableException, CredentialsException {
  // Create an invocation handler that does the actual work.
  ProxyInvocationHandler handler
      = new ProxyInvocationHandler(socketFactoryProvider,
                                   host,
                                   port,
                                   userName,
                                   password,
                                   eventFilter,
                                   eventPollInterval,
                                   eventPollTimeout);
  // Return a proxy instance with the created handler.
  // Create a proxy instance with the handler and return it.
  KernelProxy proxy
      = (KernelProxy) Proxy.newProxyInstance(Kernel.class.getClassLoader(),
                                             new Class<?>[] {KernelProxy.class},
                                             handler);
  proxy.login();
  return proxy;
}
 
Example #10
Source File: InstantiationUtilTest.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
@Test
public void testResolveProxyClass() throws Exception {
	final String interfaceName = "UserDefinedInterface";
	final String proxyName = "UserProxy";

	try (URLClassLoader userClassLoader = createClassLoader(interfaceName, proxyName)) {
		Class<?> userInterface = Class.forName(interfaceName, false, userClassLoader);
		InvocationHandler userProxy = (InvocationHandler) Class.forName(proxyName, false, userClassLoader)
			.newInstance();

		Object proxy = Proxy.newProxyInstance(userClassLoader, new Class[]{userInterface}, userProxy);

		byte[] serializeObject = InstantiationUtil.serializeObject(proxy);
		Object deserializedProxy = InstantiationUtil.deserializeObject(serializeObject, userClassLoader);
		assertNotNull(deserializedProxy);
	}
}
 
Example #11
Source File: CachingRelMetadataProvider.java    From Quicksql with MIT License 6 votes vote down vote up
public <M extends Metadata> UnboundMetadata<M> apply(
    Class<? extends RelNode> relClass,
    final Class<? extends M> metadataClass) {
  final UnboundMetadata<M> function =
      underlyingProvider.apply(relClass, metadataClass);
  if (function == null) {
    return null;
  }

  // TODO jvs 30-Mar-2006: Use meta-metadata to decide which metadata
  // query results can stay fresh until the next Ice Age.
  return (rel, mq) -> {
    final Metadata metadata = function.bind(rel, mq);
    return metadataClass.cast(
        Proxy.newProxyInstance(metadataClass.getClassLoader(),
            new Class[]{metadataClass},
            new CachingInvocationHandler(metadata)));
  };
}
 
Example #12
Source File: ProxyClassDesc.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generate proxy class descriptors.
 */
ObjectStreamClass[] genDescs() {
    ClassLoader ldr = ProxyClassDesc.class.getClassLoader();
    Class[] ifaces = new Class[3];
    Class[] a =
        new Class[] { A1.class, A2.class, A3.class, A4.class, A5.class };
    Class[] b =
        new Class[] { B1.class, B2.class, B3.class, B4.class, B5.class };
    Class[] c =
        new Class[] { C1.class, C2.class, C3.class, C4.class, C5.class };
    ObjectStreamClass[] descs =
        new ObjectStreamClass[a.length * b.length * c.length];
    int n = 0;
    for (int i = 0; i < a.length; i++) {
        ifaces[0] = a[i];
        for (int j = 0; j < b.length; j++) {
            ifaces[1] = b[j];
            for (int k = 0; k < c.length; k++) {
                ifaces[2] = c[k];
                Class proxyClass = Proxy.getProxyClass(ldr, ifaces);
                descs[n++] = ObjectStreamClass.lookup(proxyClass);
            }
        }
    }
    return descs;
}
 
Example #13
Source File: ProxyArrays.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Write and read proxy arrays to/from a stream.  The benchmark is run in
 * batches, with each batch consisting of a fixed number of read/write
 * cycles.  The ObjectOutputStream is reset after each batch of cycles has
 * completed.
 * Arguments: <array size> <# batches> <# cycles per batch>
 */
public long run(String[] args) throws Exception {
    int size = Integer.parseInt(args[0]);
    int nbatches = Integer.parseInt(args[1]);
    int ncycles = Integer.parseInt(args[2]);
    Proxy[][] arrays = genArrays(size, ncycles);
    StreamBuffer sbuf = new StreamBuffer();
    ObjectOutputStream oout =
        new ObjectOutputStream(sbuf.getOutputStream());
    ObjectInputStream oin =
        new ObjectInputStream(sbuf.getInputStream());

    doReps(oout, oin, sbuf, arrays, 1);     // warmup

    long start = System.currentTimeMillis();
    doReps(oout, oin, sbuf, arrays, nbatches);
    return System.currentTimeMillis() - start;
}
 
Example #14
Source File: UtilNamespaceHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testCircularCollectionBeansStartingWithList() {
	this.beanFactory.getBean("circularList");
	TestBean bean = (TestBean) this.beanFactory.getBean("circularCollectionBeansBean");

	List list = bean.getSomeList();
	assertTrue(Proxy.isProxyClass(list.getClass()));
	assertEquals(1, list.size());
	assertEquals(bean, list.get(0));

	Set set = bean.getSomeSet();
	assertFalse(Proxy.isProxyClass(set.getClass()));
	assertEquals(1, set.size());
	assertTrue(set.contains(bean));

	Map map = bean.getSomeMap();
	assertFalse(Proxy.isProxyClass(map.getClass()));
	assertEquals(1, map.size());
	assertEquals(bean, map.get("foo"));
}
 
Example #15
Source File: TestUtils.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #16
Source File: ProxyFactory.java    From healenium-web with Apache License 2.0 5 votes vote down vote up
public static <T extends WebDriver> SelfHealingDriver createDriverProxy(ClassLoader loader, InvocationHandler handler, Class<T> clazz) {
    Class<?>[] interfaces = Stream.concat(
        Arrays.stream(clazz.getInterfaces()),
        Stream.of(JavascriptExecutor.class, SelfHealingDriver.class, HasInputDevices.class, Interactive.class)
    ).distinct().toArray(Class[]::new);

    return (SelfHealingDriver) Proxy.newProxyInstance(loader, interfaces, handler);
}
 
Example #17
Source File: SharedEntityManagerCreator.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Create a transactional EntityManager proxy for the given EntityManagerFactory.
 * @param emf the EntityManagerFactory to obtain EntityManagers from as needed
 * @param properties the properties to be passed into the
 * {@code createEntityManager} call (may be {@code null})
 * @param synchronizedWithTransaction whether to automatically join ongoing
 * transactions (according to the JPA 2.1 SynchronizationType rules)
 * @param entityManagerInterfaces the interfaces to be implemented by the
 * EntityManager. Allows the addition or specification of proprietary interfaces.
 * @return a shareable transactional EntityManager proxy
 * @since 4.0
 */
public static EntityManager createSharedEntityManager(EntityManagerFactory emf, @Nullable Map<?, ?> properties,
		boolean synchronizedWithTransaction, Class<?>... entityManagerInterfaces) {

	ClassLoader cl = null;
	if (emf instanceof EntityManagerFactoryInfo) {
		cl = ((EntityManagerFactoryInfo) emf).getBeanClassLoader();
	}
	Class<?>[] ifcs = new Class<?>[entityManagerInterfaces.length + 1];
	System.arraycopy(entityManagerInterfaces, 0, ifcs, 0, entityManagerInterfaces.length);
	ifcs[entityManagerInterfaces.length] = EntityManagerProxy.class;
	return (EntityManager) Proxy.newProxyInstance(
			(cl != null ? cl : SharedEntityManagerCreator.class.getClassLoader()),
			ifcs, new SharedEntityManagerInvocationHandler(emf, properties, synchronizedWithTransaction));
}
 
Example #18
Source File: LoadProxyClasses.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public void checkLoad(Proxy proxy, ClassLoader expectedLoader) {
    ClassLoader ifaceLoader =
        proxy.getClass().getInterfaces()[0].getClassLoader();
    ClassLoader proxyLoader = proxy.getClass().getClassLoader();

    boolean proxyOk = false;

    if (boomerangSemantics) {
        ClassLoader ctxLoader =
            Thread.currentThread().getContextClassLoader();
        if (proxyLoader == ctxLoader) {
            proxyOk = true;
        }
    } else if (proxyLoader.getClass().
               getName().indexOf("sun.rmi") >= 0)
    {
        proxyOk = true;
    }

    if (proxyOk) {
        System.err.println("\ncase3: proxy loaded in" +
                           " correct loader: " + proxyLoader +
                           Arrays.asList(((URLClassLoader)
                                         proxyLoader).getURLs()));
    } else {
        TestLibrary.bomb("case3: proxy class loaded in " +
                         "incorrect loader: " + proxyLoader +
                           Arrays.asList(((URLClassLoader)
                                          proxyLoader).getURLs()));
    }

    if (ifaceLoader == expectedLoader) {
        System.err.println("case3: proxy interface loaded in" +
                           " correct loader: " + ifaceLoader);
    } else {
        TestLibrary.bomb("public proxy interface loaded in " +
                         "incorrect loader: " + ifaceLoader);
    }
}
 
Example #19
Source File: LocalStatelessSessionProxyFactoryBeanTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testInvokesMethodOnEjb3StyleBean() throws Exception {
	final int value = 11;
	final String jndiName = "foo";

	final MyEjb myEjb = mock(MyEjb.class);
	given(myEjb.getValue()).willReturn(value);

	JndiTemplate jt = new JndiTemplate() {
		@Override
		public Object lookup(String name) throws NamingException {
			// parameterize
			assertTrue(name.equals("java:comp/env/" + jndiName));
			return myEjb;
		}
	};

	LocalStatelessSessionProxyFactoryBean fb = new LocalStatelessSessionProxyFactoryBean();
	fb.setJndiName(jndiName);
	fb.setResourceRef(true);
	fb.setBusinessInterface(MyBusinessMethods.class);
	fb.setJndiTemplate(jt);

	// Need lifecycle methods
	fb.afterPropertiesSet();

	MyBusinessMethods mbm = (MyBusinessMethods) fb.getObject();
	assertTrue(Proxy.isProxyClass(mbm.getClass()));
	assertTrue(mbm.getValue() == value);
}
 
Example #20
Source File: Util.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a proxy for the specified implClass.
 *
 * If both of the following criteria is satisfied, a dynamic proxy for
 * the specified implClass is returned (otherwise a RemoteStub instance
 * for the specified implClass is returned):
 *
 *    a) either the property java.rmi.server.ignoreStubClasses is true or
 *       a pregenerated stub class does not exist for the impl class, and
 *    b) forceStubUse is false.
 *
 * If the above criteria are satisfied, this method constructs a
 * dynamic proxy instance (that implements the remote interfaces of
 * implClass) constructed with a RemoteObjectInvocationHandler instance
 * constructed with the clientRef.
 *
 * Otherwise, this method loads the pregenerated stub class (which
 * extends RemoteStub and implements the remote interfaces of
 * implClass) and constructs an instance of the pregenerated stub
 * class with the clientRef.
 *
 * @param implClass the class to obtain remote interfaces from
 * @param clientRef the remote ref to use in the invocation handler
 * @param forceStubUse if true, forces creation of a RemoteStub
 * @throws IllegalArgumentException if implClass implements illegal
 * remote interfaces
 * @throws StubNotFoundException if problem locating/creating stub or
 * creating the dynamic proxy instance
 **/
public static Remote createProxy(Class<?> implClass,
                                 RemoteRef clientRef,
                                 boolean forceStubUse)
    throws StubNotFoundException
{
    Class<?> remoteClass;

    try {
        remoteClass = getRemoteClass(implClass);
    } catch (ClassNotFoundException ex ) {
        throw new StubNotFoundException(
            "object does not implement a remote interface: " +
            implClass.getName());
    }

    if (forceStubUse ||
        !(ignoreStubClasses || !stubClassExists(remoteClass)))
    {
        return createStub(remoteClass, clientRef);
    }

    final ClassLoader loader = implClass.getClassLoader();
    final Class<?>[] interfaces = getRemoteInterfaces(implClass);
    final InvocationHandler handler =
        new RemoteObjectInvocationHandler(clientRef);

    /* REMIND: private remote interfaces? */

    try {
        return AccessController.doPrivileged(new PrivilegedAction<Remote>() {
            public Remote run() {
                return (Remote) Proxy.newProxyInstance(loader,
                                                       interfaces,
                                                       handler);
            }});
    } catch (IllegalArgumentException e) {
        throw new StubNotFoundException("unable to create proxy", e);
    }
}
 
Example #21
Source File: AutoProxyCreatorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testBeanNameAutoProxyCreatorWithFactoryBeanProxy() {
	StaticApplicationContext sac = new StaticApplicationContext();
	sac.registerSingleton("testInterceptor", TestInterceptor.class);

	RootBeanDefinition proxyCreator = new RootBeanDefinition(BeanNameAutoProxyCreator.class);
	proxyCreator.getPropertyValues().add("interceptorNames", "testInterceptor");
	proxyCreator.getPropertyValues().add("beanNames", "singletonToBeProxied,&singletonFactoryToBeProxied");
	sac.getDefaultListableBeanFactory().registerBeanDefinition("beanNameAutoProxyCreator", proxyCreator);

	RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
	sac.getDefaultListableBeanFactory().registerBeanDefinition("singletonToBeProxied", bd);

	sac.registerSingleton("singletonFactoryToBeProxied", DummyFactory.class);

	sac.refresh();

	ITestBean singletonToBeProxied = (ITestBean) sac.getBean("singletonToBeProxied");
	assertTrue(Proxy.isProxyClass(singletonToBeProxied.getClass()));

	TestInterceptor ti = (TestInterceptor) sac.getBean("testInterceptor");
	int initialNr = ti.nrOfInvocations;
	singletonToBeProxied.getName();
	assertEquals(initialNr + 1, ti.nrOfInvocations);

	FactoryBean<?> factory = (FactoryBean<?>) sac.getBean("&singletonFactoryToBeProxied");
	assertTrue(Proxy.isProxyClass(factory.getClass()));
	TestBean tb = (TestBean) sac.getBean("singletonFactoryToBeProxied");
	assertFalse(AopUtils.isAopProxy(tb));
	assertEquals(initialNr + 3, ti.nrOfInvocations);
	tb.getAge();
	assertEquals(initialNr + 3, ti.nrOfInvocations);
}
 
Example #22
Source File: Proxy1.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // 代理类
    Class<?> proxyClass = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
    // 构造方法
    Constructor<?>[] constructors = proxyClass.getConstructors();
    for (Constructor<?> constructor : constructors) {
        System.out.println(constructor);
    }
    // 普通方法
    Method[] methods = proxyClass.getMethods();
    for (Method method : methods) {
        System.out.println(method);
    }
}
 
Example #23
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 #24
Source File: DefaultMXBeanMappingFactory.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
final Object fromCompositeData(CompositeData cd,
                               String[] itemNames,
                               MXBeanMapping[] converters) {
    final Class<?> targetClass = getTargetClass();
    return
        Proxy.newProxyInstance(targetClass.getClassLoader(),
                               new Class<?>[] {targetClass},
                               new CompositeDataInvocationHandler(cd));
}
 
Example #25
Source File: Test.java    From native-obfuscator with GNU General Public License v3.0 5 votes vote down vote up
public void test() {
String str = "This is test string.";
CharSequence csec = null;
InvocationHandler handler = new MyHandler(str);

System.out.println("Start test ... ");

csec = (CharSequence)Proxy.newProxyInstance(
        this.getClass().getClassLoader(), new Class[] { 
    CharSequence.class }, handler);
    System.out.println(csec.charAt(15));        
    System.out.println("PASSED!");
}
 
Example #26
Source File: ConfigurationClassEnhancer.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private Object createInterfaceProxyForFactoryBean(final Object factoryBean, Class<?> interfaceType,
		final ConfigurableBeanFactory beanFactory, final String beanName) {

	return Proxy.newProxyInstance(
			factoryBean.getClass().getClassLoader(), new Class<?>[] {interfaceType},
			(proxy, method, args) -> {
				if (method.getName().equals("getObject") && args == null) {
					return beanFactory.getBean(beanName);
				}
				return ReflectionUtils.invokeMethod(method, factoryBean, args);
			});
}
 
Example #27
Source File: JavaInstanceCache.java    From jvm-sandbox-repeater with Apache License 2.0 5 votes vote down vote up
/**
 * 根据实例的类名缓存
 * <p>
 * 注意问题:
 * 1. 多实例问题可能导致回放失败
 * </p>
 *
 * @param instance 实例
 */
static void cacheInstance(Object instance) {
    if (instance != null) {
        Class<?> clazz;
        if (Proxy.isProxyClass(instance.getClass())) {
            clazz = Proxy.getInvocationHandler(instance).getClass();
        } else {
            clazz = instance.getClass();
        }
        CACHED.put(clazz.getCanonicalName(), instance);
    }
}
 
Example #28
Source File: ReplicationStream.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * ObjectInputStream.resolveProxyClass has some funky way of using
 * the incorrect class loader to resolve proxy classes, let's do it our way instead
 */
@Override
protected Class<?> resolveProxyClass(String[] interfaces)
        throws IOException, ClassNotFoundException {

    ClassLoader latestLoader;
    if (classLoaders != null && classLoaders.length > 0) {
        latestLoader = classLoaders[0];
    } else {
        latestLoader = null;
    }
    ClassLoader nonPublicLoader = null;
    boolean hasNonPublicInterface = false;

    // define proxy in class loader of non-public interface(s), if any
    Class<?>[] classObjs = new Class[interfaces.length];
    for (int i = 0; i < interfaces.length; i++) {
        Class<?> cl = this.resolveClass(interfaces[i]);
        if (latestLoader==null) latestLoader = cl.getClassLoader();
        if ((cl.getModifiers() & Modifier.PUBLIC) == 0) {
            if (hasNonPublicInterface) {
                if (nonPublicLoader != cl.getClassLoader()) {
                    throw new IllegalAccessError(
                            sm.getString("replicationStream.conflict"));
                }
            } else {
                nonPublicLoader = cl.getClassLoader();
                hasNonPublicInterface = true;
            }
        }
        classObjs[i] = cl;
    }
    try {
        return Proxy.getProxyClass(hasNonPublicInterface ? nonPublicLoader
                : latestLoader, classObjs);
    } catch (IllegalArgumentException e) {
        throw new ClassNotFoundException(null, e);
    }
}
 
Example #29
Source File: AnnotationMethodMatcher.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public boolean matches(Method method, Class<?> targetClass) {
	if (matchesMethod(method)) {
		return true;
	}
	// Proxy classes never have annotations on their redeclared methods.
	if (Proxy.isProxyClass(targetClass)) {
		return false;
	}
	// The method may be on an interface, so let's check on the target class as well.
	Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass);
	return (specificMethod != method && matchesMethod(specificMethod));
}
 
Example #30
Source File: LocalStatelessSessionProxyFactoryBeanTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testInvokesMethodOnEjb3StyleBean() throws Exception {
	final int value = 11;
	final String jndiName = "foo";

	final MyEjb myEjb = mock(MyEjb.class);
	given(myEjb.getValue()).willReturn(value);

	JndiTemplate jt = new JndiTemplate() {
		@Override
		public Object lookup(String name) throws NamingException {
			// parameterize
			assertTrue(name.equals("java:comp/env/" + jndiName));
			return myEjb;
		}
	};

	LocalStatelessSessionProxyFactoryBean fb = new LocalStatelessSessionProxyFactoryBean();
	fb.setJndiName(jndiName);
	fb.setResourceRef(true);
	fb.setBusinessInterface(MyBusinessMethods.class);
	fb.setJndiTemplate(jt);

	// Need lifecycle methods
	fb.afterPropertiesSet();

	MyBusinessMethods mbm = (MyBusinessMethods) fb.getObject();
	assertTrue(Proxy.isProxyClass(mbm.getClass()));
	assertTrue(mbm.getValue() == value);
}