Java Code Examples for java.lang.reflect.Proxy.getProxyClass()

The following are Jave code examples for showing how to use getProxyClass() of the java.lang.reflect.Proxy class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: jdk8u-jdk   File: NonPublicProxyClass.java   Source Code and License Vote up 7 votes
public void run() throws Exception {
    boolean hasAccess = loader != null || hasAccess();
    try {
        proxyClass = Proxy.getProxyClass(loader, interfaces);
        if (!hasAccess) {
            throw new RuntimeException("should have no permission to create proxy class");
        }
    } catch (AccessControlException e) {
        if (hasAccess) {
            throw e;
        }
        if (e.getPermission().getClass() != RuntimePermission.class ||
                !e.getPermission().getName().equals("getClassLoader")) {
            throw e;
        }
        return;
    }

    if (Modifier.isPublic(proxyClass.getModifiers())) {
        throw new RuntimeException(proxyClass + " must be non-public");
    }
    newProxyInstance();
    newInstanceFromConstructor(proxyClass);
}
 
Example 2
Project: jdk8u-jdk   File: ProxyArrays.java   Source Code and License Vote up 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 3
Project: HL4A   File: VMBridge_jdk15.java   Source Code and License Vote up 6 votes
@Override
protected Object getInterfaceProxyHelper(ContextFactory cf,
                                         Class<?>[] interfaces)
{
    // XXX: How to handle interfaces array withclasses from different
    // class loaders? Using cf.getApplicationClassLoader() ?
    ClassLoader loader = interfaces[0].getClassLoader();
    Class<?> cl = Proxy.getProxyClass(loader, interfaces);
    Constructor<?> c;
    try {
        c = cl.getConstructor(new Class[] { InvocationHandler.class });
    } catch (NoSuchMethodException ex) {
        // Should not happen
        throw Kit.initCause(new IllegalStateException(), ex);
    }
    return c;
}
 
Example 4
Project: openjdk-jdk10   File: ProxyModuleMapping.java   Source Code and License Vote up 6 votes
void verifyProxyClass() throws Exception {
    Class<?> c = Proxy.getProxyClass(loader, interfaces);
    Module m = c.getModule();
    if (target != null && m != target) {
        throw new RuntimeException(c.getModule() + " not expected: " + target);
    }
    // expect dynamic module
    if (target == null && (!m.isNamed() || !m.getName().startsWith("jdk.proxy"))) {
        throw new RuntimeException("Unexpected:" + m);
    }

    Module module = c.getModule();
    try {
        Constructor<?> cons = c.getConstructor(InvocationHandler.class);
        cons.newInstance(ih);
        if (module.isNamed()) {
            throw new RuntimeException("expected IAE not thrown");
        }
    } catch (IllegalAccessException e) {
        if (!module.isNamed()) {
            throw e;
        }
    }
}
 
Example 5
Project: tomcat7   File: CustomObjectInputStream.java   Source Code and License Vote up 6 votes
/**
 * Return a proxy class that implements the interfaces named in a proxy
 * class descriptor. Do this using the class loader assigned to this
 * Context.
 */
@Override
protected Class<?> resolveProxyClass(String[] interfaces)
        throws IOException, ClassNotFoundException {

    Class<?>[] cinterfaces = new Class[interfaces.length];
    for (int i = 0; i < interfaces.length; i++) {
        cinterfaces[i] = classLoader.loadClass(interfaces[i]);
    }

    try {
        return Proxy.getProxyClass(classLoader, cinterfaces);
    } catch (IllegalArgumentException e) {
        throw new ClassNotFoundException(null, e);
    }
}
 
Example 6
Project: gate-core   File: GateAwareObjectInputStream.java   Source Code and License Vote up 6 votes
/**
 * Resolve a proxy class that implements the given interfaces. First
 * attempts to use the default resolution method provided by
 * ObjectInputStream. If that fails with a ClassNotFoundException then
 * tries to resolve the interfaces and create the proxy class using
 * the GATE classloader instead.
 */
@Override
protected Class<?> resolveProxyClass(String[] interfaces) throws IOException,
        ClassNotFoundException {
  try {
    return super.resolveProxyClass(interfaces);
  }
  catch(ClassNotFoundException cnfe) {
    // failed to load with the normal method, try the GATE ClassLoader
    // instead
    Class<?>[] interfaceClasses = new Class<?>[interfaces.length];
    for(int i = 0; i < interfaces.length; i++) {
      interfaceClasses[i] = Class.forName(interfaces[i], false, Gate
              .getClassLoader());
    }
    return Proxy.getProxyClass(Gate.getClassLoader(), interfaceClasses);
  }
}
 
Example 7
Project: openjdk-jdk10   File: Obj.java   Source Code and License Vote up 5 votes
protected Class<?> resolveProxyClass(String[] interfaces) throws
       IOException, ClassNotFoundException {
    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 = Class.forName(interfaces[i], false, classLoader);
        if ((cl.getModifiers() & Modifier.PUBLIC) == 0) {
            if (hasNonPublicInterface) {
                if (nonPublicLoader != cl.getClassLoader()) {
                    throw new IllegalAccessError(
                       "conflicting non-public interface class loaders");
                }
            } else {
                nonPublicLoader = cl.getClassLoader();
                hasNonPublicInterface = true;
            }
        }
        classObjs[i] = cl;
    }
    try {
        @SuppressWarnings("deprecation")
        Class<?> proxyClass = Proxy.getProxyClass(hasNonPublicInterface ?
               nonPublicLoader : classLoader, classObjs);
        return proxyClass;
    } catch (IllegalArgumentException e) {
        throw new ClassNotFoundException(null, e);
    }
}
 
Example 8
Project: incubator-netbeans   File: WeakListenerImpl.java   Source Code and License Vote up 5 votes
/** @param listener listener to delegate to
*/
ProxyListener(Class<?> c, Class<?> api, EventListener listener) {
    super(api, listener);

    try {
        Reference<Constructor<?>> ref = constructors.get(c);
        Constructor<?> proxyConstructor = ref == null ? null : ref.get();

        if (proxyConstructor == null) {
            Class<?> proxyClass = Proxy.getProxyClass(c.getClassLoader(), c);
            proxyConstructor = proxyClass.getConstructor(InvocationHandler.class);
            proxyConstructor.setAccessible(true);
            constructors.put(c, new SoftReference<Constructor<?>>(proxyConstructor));
        }

        Object p;

        try {
            p = proxyConstructor.newInstance(this);
        } catch (NoClassDefFoundError err) {
            // if for some reason the actual creation of the instance
            // from constructor fails, try it once more using regular
            // method, see issue 30449
            p = Proxy.newProxyInstance(c.getClassLoader(), new Class<?>[] { c }, this);
        }

        proxy = p;
    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example 9
Project: apache-tomcat-7.0.73-with-comment   File: StatementDecoratorInterceptor.java   Source Code and License Vote up 5 votes
protected Constructor<?> getResultSetConstructor() throws NoSuchMethodException {
    if (resultSetConstructor == null) {
        Class<?> proxyClass = Proxy.getProxyClass(StatementDecoratorInterceptor.class.getClassLoader(),
                new Class[] { ResultSet.class });
        resultSetConstructor = proxyClass.getConstructor(new Class[] { InvocationHandler.class });
    }
    return resultSetConstructor;
}
 
Example 10
Project: lams   File: CustomObjectInputStream.java   Source Code and License Vote up 5 votes
/**
 * Return a proxy class that implements the interfaces named in a proxy
 * class descriptor. Do this using the class loader assigned to this
 * Context.
 */
protected Class resolveProxyClass(String[] interfaces)
    throws IOException, ClassNotFoundException {

    Class[] cinterfaces = new Class[interfaces.length];
    for (int i = 0; i < interfaces.length; i++)
        cinterfaces[i] = classLoader.loadClass(interfaces[i]);

    try {
        return Proxy.getProxyClass(classLoader, cinterfaces);
    } catch (IllegalArgumentException e) {
        throw new ClassNotFoundException(null, e);
    }
}
 
Example 11
Project: lazycat   File: DataSourceLinkFactory.java   Source Code and License Vote up 5 votes
protected Object wrapDataSource(Object datasource, String username, String password) throws NamingException {
	try {
		Class<?> proxyClass = Proxy.getProxyClass(datasource.getClass().getClassLoader(),
				datasource.getClass().getInterfaces());
		Constructor<?> proxyConstructor = proxyClass.getConstructor(new Class[] { InvocationHandler.class });
		DataSourceHandler handler = new DataSourceHandler((DataSource) datasource, username, password);
		return proxyConstructor.newInstance(handler);
	} catch (Exception x) {
		if (x instanceof InvocationTargetException) {
			Throwable cause = x.getCause();
			if (cause instanceof ThreadDeath) {
				throw (ThreadDeath) cause;
			}
			if (cause instanceof VirtualMachineError) {
				throw (VirtualMachineError) cause;
			}
			if (cause instanceof Exception) {
				x = (Exception) cause;
			}
		}
		if (x instanceof NamingException)
			throw (NamingException) x;
		else {
			NamingException nx = new NamingException(x.getMessage());
			nx.initCause(x);
			throw nx;
		}
	}
}
 
Example 12
Project: tomcat7   File: DataSourceLinkFactory.java   Source Code and License Vote up 5 votes
protected Object wrapDataSource(Object datasource, String username, String password) throws NamingException {
    try {
        Class<?> proxyClass = Proxy.getProxyClass(datasource.getClass().getClassLoader(), datasource.getClass().getInterfaces());
        Constructor<?> proxyConstructor = proxyClass.getConstructor(new Class[] { InvocationHandler.class });
        DataSourceHandler handler = new DataSourceHandler((DataSource)datasource, username, password);
        return proxyConstructor.newInstance(handler);    
    }catch (Exception x) {
        if (x instanceof InvocationTargetException) {
            Throwable cause = x.getCause();
            if (cause instanceof ThreadDeath) {
                throw (ThreadDeath) cause;
            }
            if (cause instanceof VirtualMachineError) {
                throw (VirtualMachineError) cause;
            }
            if (cause instanceof Exception) {
                x = (Exception) cause;
            }
        }
        if (x instanceof NamingException) throw (NamingException)x;
        else {
            NamingException nx = new NamingException(x.getMessage());
            nx.initCause(x);
            throw nx;
        }
    }
}
 
Example 13
Project: tomcat7   File: StatementDecoratorInterceptor.java   Source Code and License Vote up 5 votes
protected Constructor<?> getResultSetConstructor() throws NoSuchMethodException {
    if (resultSetConstructor == null) {
        Class<?> proxyClass = Proxy.getProxyClass(StatementDecoratorInterceptor.class.getClassLoader(),
                new Class[] { ResultSet.class });
        resultSetConstructor = proxyClass.getConstructor(new Class[] { InvocationHandler.class });
    }
    return resultSetConstructor;
}
 
Example 14
Project: tomcat7   File: AbstractQueryReport.java   Source Code and License Vote up 5 votes
/**
 * Creates a constructor for a proxy class, if one doesn't already exist
 * @param idx - the index of the constructor
 * @param clazz - the interface that the proxy will implement
 * @return - returns a constructor used to create new instances
 * @throws NoSuchMethodException
 */
protected Constructor<?> getConstructor(int idx, Class<?> clazz) throws NoSuchMethodException {
    if (constructors[idx]==null) {
        Class<?> proxyClass = Proxy.getProxyClass(SlowQueryReport.class.getClassLoader(), new Class[] {clazz});
        constructors[idx] = proxyClass.getConstructor(new Class[] { InvocationHandler.class });
    }
    return constructors[idx];
}
 
Example 15
Project: OpenJSharp   File: LoaderHandler.java   Source Code and License Vote up 5 votes
/**
 * Define a proxy class in the given class loader.  The proxy
 * class will implement the given interfaces Classes.
 */
private static Class<?> loadProxyClass(ClassLoader loader, Class<?>[] interfaces)
    throws ClassNotFoundException
{
    try {
        return Proxy.getProxyClass(loader, interfaces);
    } catch (IllegalArgumentException e) {
        throw new ClassNotFoundException(
            "error creating dynamic proxy class", e);
    }
}
 
Example 16
Project: iron   File: ProxyConstructorFactory.java   Source Code and License Vote up 5 votes
private static <T> Constructor<T> createProxyConstructor(@Nullable LoadingCache<CacheKey, ClassLoader> cache, Class<T> interfaceClass,
                                                         Class<?>... otherInterfaceClasses) {
    Class<?>[] interfaceClasses = new Class[1 + otherInterfaceClasses.length];
    interfaceClasses[0] = interfaceClass;
    ClassLoader classLoader;
    if (otherInterfaceClasses.length == 0) {
        classLoader = interfaceClass.getClassLoader();
    } else {
        System.arraycopy(otherInterfaceClasses, 0, interfaceClasses, 1, otherInterfaceClasses.length);

        List<ClassLoader> classLoaders = extractClassloaderList(interfaceClasses);
        if (classLoaders.size() == 1) {
            classLoader = classLoaders.get(0);
        } else if (cache != null) {
            classLoader = cache.getUnchecked(new CacheKey(classLoaders));
        } else {
            classLoader = createClassLoader(classLoaders);
        }
    }
    Class<?> uncheckedProxyClass = Proxy.getProxyClass(classLoader, interfaceClasses);
    Class<T> proxyClass = interfaceClass.getClass().cast(uncheckedProxyClass);
    try {
        return proxyClass.getConstructor(InvocationHandler.class);
    } catch (NoSuchMethodException e) {
        throw new StoreException(e);
    }
}
 
Example 17
Project: monarch   File: InternalDataSerializer.java   Source Code and License Vote up 5 votes
@Override
protected Class resolveProxyClass(String[] interfaces)
    throws IOException, ClassNotFoundException {

  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 = getCachedClass(interfaces[i]);
    if ((cl.getModifiers() & Modifier.PUBLIC) == 0) {
      if (hasNonPublicInterface) {
        if (nonPublicLoader != cl.getClassLoader()) {
          String s = "conflicting non-public interface class loaders";
          throw new IllegalAccessError(s);
        }

      } else {
        nonPublicLoader = cl.getClassLoader();
        hasNonPublicInterface = true;
      }
    }
    classObjs[i] = cl;
  }

  try {
    if (hasNonPublicInterface) {
      return Proxy.getProxyClass(nonPublicLoader, classObjs);
    } else {
      return ClassPathLoader.getLatest().getProxyClass(classObjs);
    }
  } catch (IllegalArgumentException e) {
    throw new ClassNotFoundException(null, e);
  }
}
 
Example 18
Project: lazycat   File: ReplicationStream.java   Source Code and License Vote up 5 votes
/**
 * 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("conflicting non-public interface class loaders");
				}
			} 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 19
Project: apache-tomcat-7.0.73-with-comment   File: AbstractQueryReport.java   Source Code and License Vote up 5 votes
/**
 * Creates a constructor for a proxy class, if one doesn't already exist
 * @param idx - the index of the constructor
 * @param clazz - the interface that the proxy will implement
 * @return - returns a constructor used to create new instances
 * @throws NoSuchMethodException
 */
protected Constructor<?> getConstructor(int idx, Class<?> clazz) throws NoSuchMethodException {
    if (constructors[idx]==null) {
        Class<?> proxyClass = Proxy.getProxyClass(SlowQueryReport.class.getClassLoader(), new Class[] {clazz});
        constructors[idx] = proxyClass.getConstructor(new Class[] { InvocationHandler.class });
    }
    return constructors[idx];
}
 
Example 20
Project: OpenJSharp   File: TransferableProxy.java   Source Code and License Vote up 4 votes
protected Class<?> resolveProxyClass(String[] interfaces)
  throws IOException, ClassNotFoundException {

    Set<String> s = new HashSet<String>(interfaces.length);
    for (int i = 0; i < interfaces.length; i++) {
        s.add(interfaces[i]);
    }

    ClassLoader classLoader = map.get(s);
    if (classLoader == null) {
        return super.resolveProxyClass(interfaces);
    }

    // The code below is mostly copied from the superclass.
    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 = Class.forName(interfaces[i], false, classLoader);
        if ((cl.getModifiers() & Modifier.PUBLIC) == 0) {
            if (hasNonPublicInterface) {
                if (nonPublicLoader != cl.getClassLoader()) {
                    throw new IllegalAccessError(
                        "conflicting non-public interface class loaders");
                }
            } else {
                nonPublicLoader = cl.getClassLoader();
                hasNonPublicInterface = true;
            }
        }
        classObjs[i] = cl;
    }
    try {
        return Proxy.getProxyClass(hasNonPublicInterface ?
                                   nonPublicLoader : classLoader,
                                   classObjs);
    } catch (IllegalArgumentException e) {
        throw new ClassNotFoundException(null, e);
    }
}