Java 类java.lang.reflect.Proxy 实例源码

项目:the-vigilantes    文件:JDBC4ConnectionWrapper.java   
/**
 * Returns an object that implements the given interface to allow access to
 * non-standard methods, or standard methods not exposed by the proxy. The
 * result may be either the object found to implement the interface or a
 * proxy for that object. If the receiver implements the interface then that
 * is the object. If the receiver is a wrapper and the wrapped object
 * implements the interface then that is the object. Otherwise the object is
 * the result of calling <code>unwrap</code> recursively on the wrapped
 * object. If the receiver is not a wrapper and does not implement the
 * interface, then an <code>SQLException</code> is thrown.
 * 
 * @param iface
 *            A Class defining an interface that the result must implement.
 * @return an object that implements the interface. May be a proxy for the
 *         actual implementing object.
 * @throws java.sql.SQLException
 *             If no object found that implements the interface
 * @since 1.6
 */
public synchronized <T> T unwrap(java.lang.Class<T> iface) throws java.sql.SQLException {
    try {
        if ("java.sql.Connection".equals(iface.getName()) || "java.sql.Wrapper.class".equals(iface.getName())) {
            return iface.cast(this);
        }

        if (unwrappedInterfaces == null) {
            unwrappedInterfaces = new HashMap<Class<?>, Object>();
        }

        Object cachedUnwrapped = unwrappedInterfaces.get(iface);

        if (cachedUnwrapped == null) {
            cachedUnwrapped = Proxy.newProxyInstance(this.mc.getClass().getClassLoader(), new Class<?>[] { iface },
                    new ConnectionErrorFiringInvocationHandler(this.mc));
            unwrappedInterfaces.put(iface, cachedUnwrapped);
        }

        return iface.cast(cachedUnwrapped);
    } catch (ClassCastException cce) {
        throw SQLError.createSQLException("Unable to unwrap to " + iface.toString(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
    }
}
项目:OpenJSharp    文件:Class.java   
private void checkPackageAccess(final ClassLoader ccl, boolean checkProxyInterfaces) {
    final SecurityManager s = System.getSecurityManager();
    if (s != null) {
        final ClassLoader cl = getClassLoader0();

        if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) {
            String name = this.getName();
            int i = name.lastIndexOf('.');
            if (i != -1) {
                // skip the package access check on a proxy class in default proxy package
                String pkg = name.substring(0, i);
                if (!Proxy.isProxyClass(this) || ReflectUtil.isNonPublicProxyClass(this)) {
                    s.checkPackageAccess(pkg);
                }
            }
        }
        // check package access on the proxy interfaces
        if (checkProxyInterfaces && Proxy.isProxyClass(this)) {
            ReflectUtil.checkProxyPackageAccess(ccl, this.getInterfaces());
        }
    }
}
项目:GitHub    文件:DistinctUntilChangedInterceptor.java   
@SuppressWarnings("unchecked")
@NonNull
public <V extends TiView> V wrap(@NonNull final V view) {

    Class<?> foundInterfaceClass =
            getInterfaceOfClassExtendingGivenInterface(view.getClass(), TiView.class);
    if (foundInterfaceClass == null) {
        throw new IllegalStateException("the interface extending View could not be found");
    }

    if (!hasObjectMethodWithAnnotation(view, DistinctUntilChanged.class)) {
        // not method has the annotation, returning original view
        // not creating a proxy
        return view;
    }

    return (V) Proxy.newProxyInstance(
            foundInterfaceClass.getClassLoader(), new Class<?>[]{foundInterfaceClass},
            new DistinctUntilChangedInvocationHandler<>(view));
}
项目:openjdk-jdk10    文件:SerialFilterTest.java   
@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;
}
项目:jdk8u-jdk    文件:RuntimeExceptionTest.java   
/**
 * Test the monitor notifications.
 */
public int monitorNotifications() throws Exception {

    server = MBeanServerFactory.newMBeanServer();

    MBeanServerForwarderInvocationHandler mbsfih =
        (MBeanServerForwarderInvocationHandler)
        Proxy.getInvocationHandler(server);

    mbsfih.setGetAttributeException(
        new RuntimeException("Test RuntimeException"));

    domain = server.getDefaultDomain();

    obsObjName = ObjectName.getInstance(domain + ":type=ObservedObject");
    server.registerMBean(new ObservedObject(), obsObjName);

    echo(">>> ----------------------------------------");
    int error = counterMonitorNotification();
    echo(">>> ----------------------------------------");
    error += gaugeMonitorNotification();
    echo(">>> ----------------------------------------");
    error += stringMonitorNotification();
    echo(">>> ----------------------------------------");
    return error;
}
项目:ProyectoPacientes    文件:WrapperBase.java   
/**
 * Recursively checks for interfaces on the given object to determine
 * if it implements a java.sql interface, and if so, proxies the
 * instance so that we can catch and fire SQL errors.
 * 
 * @param toProxy
 * @param clazz
 */
private Object proxyIfInterfaceIsJdbc(Object toProxy, Class<?> clazz) {
    Class<?>[] interfaces = clazz.getInterfaces();

    for (Class<?> iclass : interfaces) {
        String packageName = Util.getPackageName(iclass);

        if ("java.sql".equals(packageName) || "javax.sql".equals(packageName)) {
            return Proxy.newProxyInstance(toProxy.getClass().getClassLoader(), interfaces, new ConnectionErrorFiringInvocationHandler(toProxy));
        }

        return proxyIfInterfaceIsJdbc(toProxy, iclass);
    }

    return toProxy;
}
项目:whackpad    文件:VMBridge_jdk13.java   
@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;
}
项目:OpenJSharp    文件:AbstractWrapperBeanGenerator.java   
private void processXmlElement(List<Annotation> jaxb, String elemName, String elemNS, T type) {
    XmlElement elemAnn = null;
    for (Annotation a : jaxb) {
        if (a.annotationType() == XmlElement.class) {
            elemAnn = (XmlElement) a;
            jaxb.remove(a);
            break;
        }
    }
    String name = (elemAnn != null && !elemAnn.name().equals("##default"))
            ? elemAnn.name() : elemName;

    String ns = (elemAnn != null && !elemAnn.namespace().equals("##default"))
            ? elemAnn.namespace() : elemNS;

    boolean nillable = nav.isArray(type)
            || (elemAnn != null && elemAnn.nillable());

    boolean required = elemAnn != null && elemAnn.required();
    XmlElementHandler handler = new XmlElementHandler(name, ns, nillable, required);
    XmlElement elem = (XmlElement) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class<?>[]{XmlElement.class}, handler);
    jaxb.add(elem);
}
项目:openjdk-jdk10    文件:ObjectStreamClass.java   
/**
 * 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;
}
项目:the-vigilantes    文件:UtilsTest.java   
/**
 * Tests Util.isJdbcInterface()
 * 
 * @throws Exception
 */
public void testIsJdbcInterface() throws Exception {
    // Classes directly or indirectly implementing JDBC interfaces.
    assertTrue(Util.isJdbcInterface(PreparedStatement.class));
    assertTrue(Util.isJdbcInterface(StatementImpl.class));
    assertTrue(Util.isJdbcInterface(Statement.class));
    assertTrue(Util.isJdbcInterface(ResultSetImpl.class));
    Statement s = (Statement) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class<?>[] { Statement.class }, new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return null;
        }
    });
    assertTrue(Util.isJdbcInterface(s.getClass()));

    // Classes not implementing JDBC interfaces.
    assertFalse(Util.isJdbcInterface(Util.class));
    assertFalse(Util.isJdbcInterface(UtilsTest.class));

}
项目:meparty    文件:RestApiProxyFactory.java   
/**
 * Returns Rest API implementation.
 *
 * @param restApiClass type of Rest API
 * @param <T>          Rest Api type
 * @return Rest API instance
 */
@SuppressWarnings("unchecked")
public static <T extends Controller> T createProxy(Class<T> restApiClass) {
  AssertHelper.notNull(restApiClass);

  if (!restApiClass.isAnnotationPresent(RestApi.class)) {
    throw new RestApiAnnotationIsMissingException(restApiClass);
  }

  RestApi restApiAnnotation = restApiClass.getAnnotation(RestApi.class);
  String applicationName = restApiAnnotation.value();

  if (StringHelper.isNullOrEmpty(applicationName)) {
    throw new ApplicationNameCannotBeNullOrEmptyException(restApiClass);
  }

  InvocationHandler handler = new RestApiProxyInvocationHandler();

  T restApi = (T) Proxy.newProxyInstance(restApiClass.getClassLoader(),
      new Class[]{restApiClass},
      handler);

  return restApi;
}
项目:incubator-netbeans    文件:MetaInfCacheTest.java   
private static Object generateProxyType(final int i) {
    class DummyH implements InvocationHandler {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (method.getName().equals("equals")) {
                return proxy == args[0];
            }
            if (method.getName().equals("toString")) {
                return "DummyH[" + i + "]";
            }
            return null;
        }
    }
    return Proxy.newProxyInstance(
        MetaInfCache.class.getClassLoader(),
        findTypes(i), 
        new DummyH()
    );
}
项目:incubator-netbeans    文件:BlacklistedClassesHandlerSingleton.java   
/**
 * Use this method to get existing or new non-initialized instance of
 * BlacklistedClassesHandler. This method ensures that only one instance of
 * BlacklistedClassesHandler is shared across the different classloaders.
 *
 * Use initSingleton methods to initialize BlacklistedClassesHandler
 * @return existing or new non-initialized instance of
 *         BlacklistedClassesHandler
 */
public static synchronized BlacklistedClassesHandler getInstance() {
    if (instance == null) {
        try {
            // TODO Is it really necessary to use proxies?
            ClassLoader myClassLoader = BlacklistedClassesHandlerSingleton.class.getClassLoader();
            ClassLoader parentClassLoader = ClassLoader.getSystemClassLoader();
            if (myClassLoader != parentClassLoader) {
                Class otherClassInstance = parentClassLoader.loadClass(BlacklistedClassesHandlerSingleton.class.getName());
                Method getInstanceMethod = otherClassInstance.getDeclaredMethod("getInstance", new Class[] { });
                Object otherAbsoluteSingleton = getInstanceMethod.invoke(null, new Object[] { } );
                instance = (BlacklistedClassesHandler) Proxy.newProxyInstance(myClassLoader,
                                                     new Class[] { BlacklistedClassesHandler.class },
                                                     new PassThroughProxyHandler(otherAbsoluteSingleton));
            } else {
                instance = new BlacklistedClassesHandlerSingleton();
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to get BlacklistedClassesHandler instance", e);
        }
    }

    return instance;
}
项目:OpenJSharp    文件:RemoteObjectInvocationHandler.java   
/**
 * Handles java.lang.Object methods.
 **/
private Object invokeObjectMethod(Object proxy,
                                  Method method,
                                  Object[] args)
{
    String name = method.getName();

    if (name.equals("hashCode")) {
        return hashCode();

    } else if (name.equals("equals")) {
        Object obj = args[0];
        return
            proxy == obj ||
            (obj != null &&
             Proxy.isProxyClass(obj.getClass()) &&
             equals(Proxy.getInvocationHandler(obj)));

    } else if (name.equals("toString")) {
        return proxyToString(proxy);

    } else {
        throw new IllegalArgumentException(
            "unexpected Object method: " + method);
    }
}
项目:BibliotecaPS    文件:JDBC4StatementWrapper.java   
/**
 * Returns an object that implements the given interface to allow access to
 * non-standard methods, or standard methods not exposed by the proxy. The
 * result may be either the object found to implement the interface or a
 * proxy for that object. If the receiver implements the interface then that
 * is the object. If the receiver is a wrapper and the wrapped object
 * implements the interface then that is the object. Otherwise the object is
 * the result of calling <code>unwrap</code> recursively on the wrapped
 * object. If the receiver is not a wrapper and does not implement the
 * interface, then an <code>SQLException</code> is thrown.
 * 
 * @param iface
 *            A Class defining an interface that the result must implement.
 * @return an object that implements the interface. May be a proxy for the
 *         actual implementing object.
 * @throws java.sql.SQLException
 *             If no object found that implements the interface
 * @since 1.6
 */
public synchronized <T> T unwrap(java.lang.Class<T> iface) throws java.sql.SQLException {
    try {
        if ("java.sql.Statement".equals(iface.getName()) || "java.sql.Wrapper.class".equals(iface.getName())) {
            return iface.cast(this);
        }

        if (unwrappedInterfaces == null) {
            unwrappedInterfaces = new HashMap<Class<?>, Object>();
        }

        Object cachedUnwrapped = unwrappedInterfaces.get(iface);

        if (cachedUnwrapped == null) {
            cachedUnwrapped = Proxy.newProxyInstance(this.wrappedStmt.getClass().getClassLoader(), new Class<?>[] { iface },
                    new ConnectionErrorFiringInvocationHandler(this.wrappedStmt));
            unwrappedInterfaces.put(iface, cachedUnwrapped);
        }

        return iface.cast(cachedUnwrapped);
    } catch (ClassCastException cce) {
        throw SQLError.createSQLException("Unable to unwrap to " + iface.toString(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
    }
}
项目:aws-sdk-java-v2    文件:ClientConnectionManagerFactory.java   
/**
 * Returns a wrapped instance of {@link HttpClientConnectionManager}
 * to capture the necessary performance metrics.
 *
 * @param orig the target instance to be wrapped
 */
public static HttpClientConnectionManager wrap(HttpClientConnectionManager orig) {
    if (orig instanceof Wrapped) {
        throw new IllegalArgumentException();
    }
    final Class<?>[] interfaces;
    if (orig instanceof ConnPoolControl) {
        interfaces = new Class<?>[]{
                HttpClientConnectionManager.class,
                ConnPoolControl.class,
                Wrapped.class};
    } else {
        interfaces = new Class<?>[]{
                HttpClientConnectionManager.class,
                Wrapped.class
        };
    }
    return (HttpClientConnectionManager) Proxy.newProxyInstance(
            // https://github.com/aws/aws-sdk-java/pull/48#issuecomment-29454423
            ClientConnectionManagerFactory.class.getClassLoader(),
            interfaces,
            new Handler(orig));
}
项目:dremio-oss    文件:ProxiesManager.java   
private Class<Proxy> getProxyClassForInterface( final Class<?> interfaceType ) {
  assert interfaceType.isInterface();

  Class<Proxy> proxyReturnClass = interfacesToProxyClassesMap.get( interfaceType );
  if ( null == proxyReturnClass ) {

    // Suppressed because we know getProxyClass returns class extending Proxy.
    @SuppressWarnings("unchecked")
    Class<Proxy> newProxyReturnClass =
        (Class<Proxy>) Proxy.getProxyClass( interfaceType.getClassLoader(),
                                            new Class[] { interfaceType });
    interfacesToProxyClassesMap.put( interfaceType, newProxyReturnClass );
    proxyReturnClass = newProxyReturnClass;
  }
  return proxyReturnClass;
}
项目:reflection-util    文件:ClassUtils.java   
private static <T> Class<T> getRealClass(Class<T> clazz) {
    if (isProxyClass(clazz)) {
        if (Proxy.isProxyClass(clazz)) {
            Class<?>[] interfaces = clazz.getInterfaces();
            if (interfaces.length != 1) {
                throw new IllegalArgumentException("Unexpected number of interfaces: " + interfaces.length);
            }
            @SuppressWarnings("unchecked")
            Class<T> proxiedInterface = (Class<T>) interfaces[0];
            return proxiedInterface;
        }
        @SuppressWarnings("unchecked")
        Class<T> superclass = (Class<T>) clazz.getSuperclass();
        return getRealClass(superclass);
    }
    return clazz;
}
项目:ramus    文件:InternetClient.java   
@SuppressWarnings("unchecked")
private Object createDeligate(Class[] classes) {
    return Proxy.newProxyInstance(getClass().getClassLoader(), classes,
            new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method,
                                     Object[] args) throws Throwable {

                    CallParameters parameters = new CallParameters(method
                            .getName(), args);

                    Result result = connection.call(parameters);
                    if (result.exception != null)
                        throw result.exception;
                    return result.result;
                }
            });
}
项目:crnk-framework    文件:CrnkClient.java   
@SuppressWarnings("unchecked")
public <R extends ResourceRepositoryV2<?, ?>> R getRepositoryForInterface(Class<R> repositoryInterfaceClass) {
    init();
    RepositoryInformationProvider informationBuilder = moduleRegistry.getRepositoryInformationBuilder();
    PreconditionUtil.assertTrue("no a valid repository interface", informationBuilder.accept(repositoryInterfaceClass));
    ResourceRepositoryInformation repositoryInformation = (ResourceRepositoryInformation) informationBuilder
            .build(repositoryInterfaceClass, new DefaultRepositoryInformationProviderContext(moduleRegistry));
    Class<?> resourceClass = repositoryInformation.getResourceInformation().get().getResourceClass();

    Object actionStub = actionStubFactory != null ? actionStubFactory.createStub(repositoryInterfaceClass) : null;
    ResourceRepositoryV2<?, Serializable> repositoryStub = getQuerySpecRepository(resourceClass);

    ClassLoader classLoader = repositoryInterfaceClass.getClassLoader();
    InvocationHandler invocationHandler =
            new ClientStubInvocationHandler(repositoryInterfaceClass, repositoryStub, actionStub);
    return (R) Proxy.newProxyInstance(classLoader, new Class[] { repositoryInterfaceClass, ResourceRepositoryV2.class },
            invocationHandler);
}
项目:jDialects    文件:ClassUtils.java   
/**
 * Return a descriptive name for the given object's type: usually simply
 * the class name, but component type class name + "[]" for arrays,
 * and an appended list of implemented interfaces for JDK proxies.
 * @param value the value to introspect
 * @return the qualified name of the class
 */
public static String getDescriptiveType(Object value) {
    if (value == null) {
        return null;
    }
    Class<?> clazz = value.getClass();
    if (Proxy.isProxyClass(clazz)) {
        StringBuilder result = new StringBuilder(clazz.getName());
        result.append(" implementing ");
        Class<?>[] ifcs = clazz.getInterfaces();
        for (int i = 0; i < ifcs.length; i++) {
            result.append(ifcs[i].getName());
            if (i < ifcs.length - 1) {
                result.append(',');
            }
        }
        return result.toString();
    }
    else if (clazz.isArray()) {
        return getQualifiedNameForArray(clazz);
    }
    else {
        return clazz.getName();
    }
}
项目:openjdk-jdk10    文件:ScriptEngineSecurityTest.java   
@Test
public static void proxyStaticAccessCheckTest() {
    if (System.getSecurityManager() == null) {
        // pass vacuously
        return;
    }

    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final Runnable r = (Runnable)Proxy.newProxyInstance(
        ScriptEngineSecurityTest.class.getClassLoader(),
        new Class[] { Runnable.class },
        new InvocationHandler() {
            @Override
            public Object invoke(final Object p, final Method mtd, final Object[] a) {
                return null;
            }
        });

    e.put("rc", r.getClass());
    e.put("cl", ScriptEngineSecurityTest.class.getClassLoader());
    e.put("intfs", new Class[] { Runnable.class });

    // make sure static methods of Proxy is not accessible via subclass
    try {
        e.eval("rc.static.getProxyClass(cl, intfs)");
        fail("Should have thrown SecurityException");
    } catch (final Exception exp) {
        if (! (exp instanceof SecurityException)) {
            fail("SecurityException expected, got " + exp);
        }
    }
}
项目:Reer    文件:PropertyAccessorExtractionContext.java   
public List<Method> getGetters() {
    List<Method> getters;
    if (mostSpecificDeclaration.getReturnType()==Boolean.TYPE) {
        getters = Lists.newArrayList();
        for (Method getter : declaringMethods) {
            if (Proxy.isProxyClass(getter.getDeclaringClass())) {
                continue;
            }
            getters.add(getter);
        }
    } else {
        getters = Collections.singletonList(mostSpecificDeclaration);
    }
    return getters;
}
项目:KTools    文件:BaseApi.java   
protected Service createProxyService(final Service service) {
    Class<Service> serviceClass = getServiceClass();
    return (Service) Proxy.newProxyInstance(serviceClass.getClassLoader(), new Class[]{serviceClass}, new InvocationHandler() {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (NetworkUtils.isNetAvailable()) {
                return ((Flowable) method.invoke(service, args)).subscribeOn(Schedulers.io());
            } else {
                return Flowable.error(new NetworkErrorException()).subscribeOn(Schedulers.io());
            }
        }
    });
}
项目:lams    文件:JRubyScriptUtils.java   
private boolean isProxyForSameRubyObject(Object other) {
    if (!Proxy.isProxyClass(other.getClass())) {
        return false;
    }
    InvocationHandler ih = Proxy.getInvocationHandler(other);
    return (ih instanceof RubyObjectInvocationHandler &&
            this.rubyObject.equals(((RubyObjectInvocationHandler) ih).rubyObject));
}
项目:eZooKeeper    文件:ViewerFactory.java   
private static void initViewer(StructuredViewer viewer, ElementTypes elementTypes, Object input,
        IElementBinding elementBinding, IViewerType viewerType, Class<?> contentProviderInterfaceType) {

    PluggableContentProvider pluggableContentProvider = new PluggableContentProvider(viewerType, elementTypes,
            elementBinding);

    ElementTypesLabelProvider labelProvider = new ElementTypesLabelProvider(elementTypes);

    DelegatingInvocationHandler invocationHandler = new DelegatingInvocationHandler(pluggableContentProvider);

    IContentProvider contentProvider = (IContentProvider) Proxy.newProxyInstance(contentProviderInterfaceType
            .getClassLoader(), new Class[] { contentProviderInterfaceType }, invocationHandler);

    viewer.setContentProvider(contentProvider);
    viewer.setLabelProvider(labelProvider);
    viewer.setUseHashlookup(true);
    viewer.setInput(input);
}
项目:uroborosql    文件:TestConsts.java   
@SuppressWarnings("unchecked")
private static <I> I newProxy(final Class<I> interfaceType) {
    Object o = new Object();

    Method getOriginal;
    try {
        getOriginal = ProxyContainer.class.getMethod("getOriginal");
    } catch (NoSuchMethodException | SecurityException e) {
        throw new AssertionError(e);
    }

    I proxyInstance = (I) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[] {
            interfaceType, ProxyContainer.class }, (proxy, method, args) -> {
        if (getOriginal.equals(method)) {
            return o;
        }

        if (args != null) {
            for (int i = 0; i < args.length; i++) {
                if (args[i] instanceof ProxyContainer) {
                    args[i] = ((ProxyContainer) args[i]).getOriginal();
                }
            }
        }
        return method.invoke(o, args);
    });
    return proxyInstance;
}
项目:mug    文件:RetryerTest.java   
@Test public void testNulls() throws Exception {
  Stream<?> statelessStream = (Stream<?>) Proxy.newProxyInstance(
        RetryerTest.class.getClassLoader(), new Class<?>[] {Stream.class},
        (p, method, args) -> method.invoke(Stream.of(), args));
  new NullPointerTester()
      .setDefault(Stream.class, statelessStream)
      .ignore(Retryer.class.getMethod("uponReturn", Object.class, Stream.class))
      .ignore(Retryer.class.getMethod("uponReturn", Object.class, List.class))
      .testAllPublicInstanceMethods(new Retryer());
}
项目:Reer    文件:DefaultSingleRequestWorkerProcessBuilder.java   
@Override
public PROTOCOL build() {
    return protocolType.cast(Proxy.newProxyInstance(protocolType.getClassLoader(), new Class[]{protocolType}, new InvocationHandler() {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            Receiver receiver = new Receiver(getBaseName());
            try {
                WorkerProcess workerProcess = builder.build();
                workerProcess.start();
                ObjectConnection connection = workerProcess.getConnection();
                RequestProtocol requestProtocol = connection.addOutgoing(RequestProtocol.class);
                connection.addIncoming(ResponseProtocol.class, receiver);
                connection.useJavaSerializationForParameters(workerImplementation.getClassLoader());
                connection.connect();
                requestProtocol.runThenStop(method.getName(), method.getParameterTypes(), args);
                boolean hasResult = receiver.awaitNextResult();
                workerProcess.waitForStop();
                if (!hasResult) {
                    // Reached the end of input, worker has exited without failing
                    throw new IllegalStateException(String.format("No response was received from %s but the worker process has finished.", getBaseName()));
                }
            } catch (Exception e) {
                throw WorkerProcessException.runFailed(getBaseName(), e);
            }
            return receiver.getNextResult();
        }
    }));
}
项目:NotifyTools    文件:ProxyPersistenceDelegate.java   
@Override
protected boolean mutatesTo(Object oldInstance, Object newInstance) {
    if((oldInstance instanceof Proxy) && (newInstance instanceof Proxy)){
        return super.mutatesTo(oldInstance, newInstance);
    }

    return false;
}
项目:jdk8u-jdk    文件:Obj.java   
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 {
        return Proxy.getProxyClass(hasNonPublicInterface ?
               nonPublicLoader : classLoader, classObjs);
    } catch (IllegalArgumentException e) {
        throw new ClassNotFoundException(null, e);
    }
}
项目:java-codes    文件:ProxyPattern.java   
public static <T> T proxy(T target) {

            return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                    target.getClass().getInterfaces(), (proxy, method, args) -> {
                        System.out.println("前置代理,调用方法:" + method.getName()+"()");
                        Object result = method.invoke(target, args);
                        System.out.println("后置代理,方法返回:" + result);
                        return result;
                    });
        }
项目:iron    文件:ProxyConstructorFactory.java   
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);
    }
}
项目:Elasticsearch    文件:FactoryProvider2.java   
/**
 * @param factoryType  a Java interface that defines one or more create methods.
 * @param producedType a concrete type that is assignable to the return types of all factory
 *                     methods.
 */
FactoryProvider2(TypeLiteral<F> factoryType, Key<?> producedType) {
    this.producedType = producedType;

    Errors errors = new Errors();

    @SuppressWarnings("unchecked") // we imprecisely treat the class literal of T as a Class<T>
            Class<F> factoryRawType = (Class) factoryType.getRawType();

    try {
        ImmutableMap.Builder<Method, Key<?>> returnTypesBuilder = ImmutableMap.builder();
        ImmutableMap.Builder<Method, List<Key<?>>> paramTypesBuilder
                = ImmutableMap.builder();
        // TODO: also grab methods from superinterfaces
        for (Method method : factoryRawType.getMethods()) {
            Key<?> returnType = getKey(
                    factoryType.getReturnType(method), method, method.getAnnotations(), errors);
            returnTypesBuilder.put(method, returnType);
            List<TypeLiteral<?>> params = factoryType.getParameterTypes(method);
            Annotation[][] paramAnnotations = method.getParameterAnnotations();
            int p = 0;
            List<Key<?>> keys = new ArrayList<>();
            for (TypeLiteral<?> param : params) {
                Key<?> paramKey = getKey(param, method, paramAnnotations[p++], errors);
                keys.add(assistKey(method, paramKey, errors));
            }
            paramTypesBuilder.put(method, Collections.unmodifiableList(keys));
        }
        returnTypesByMethod = returnTypesBuilder.build();
        paramTypes = paramTypesBuilder.build();
    } catch (ErrorsException e) {
        throw new ConfigurationException(e.getErrors().getMessages());
    }

    factory = factoryRawType.cast(Proxy.newProxyInstance(factoryRawType.getClassLoader(),
            new Class[]{factoryRawType}, this));
}
项目:ibm-cos-sdk-java    文件:ClientConnectionRequestFactory.java   
/**
 * Returns a wrapped instance of {@link ConnectionRequest}
 * to capture the necessary performance metrics.
 * @param orig the target instance to be wrapped
 */
static ConnectionRequest wrap(ConnectionRequest orig) {
    if (orig instanceof Wrapped)
        throw new IllegalArgumentException();
    return (ConnectionRequest) Proxy.newProxyInstance(
            // https://github.com/aws/aws-sdk-java/pull/48#issuecomment-29454423
            ClientConnectionRequestFactory.class.getClassLoader(),
            interfaces,
            new Handler(orig));
}
项目:GitHub    文件:DistinctUntilChangedInterceptor.java   
@SuppressWarnings("unchecked")
@Nullable
public static DistinctUntilChangedInvocationHandler<TiView> unwrap(@NonNull final TiView view) {
    try {
        return (DistinctUntilChangedInvocationHandler) Proxy.getInvocationHandler(view);
    } catch (ClassCastException e) {
        return null;
    }
}
项目:the-vigilantes    文件:ResultSetScannerInterceptor.java   
public ResultSetInternalMethods postProcess(String sql, Statement interceptedStatement, ResultSetInternalMethods originalResultSet, Connection connection)
        throws SQLException {

    // requirement of anonymous class
    final ResultSetInternalMethods finalResultSet = originalResultSet;

    return (ResultSetInternalMethods) Proxy.newProxyInstance(originalResultSet.getClass().getClassLoader(), new Class[] { ResultSetInternalMethods.class },
            new InvocationHandler() {

                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                    if ("equals".equals(method.getName())) {
                        // Let args[0] "unwrap" to its InvocationHandler if it is a proxy.
                        return args[0].equals(this);
                    }

                    Object invocationResult = method.invoke(finalResultSet, args);

                    String methodName = method.getName();

                    if (invocationResult != null && invocationResult instanceof String || "getString".equals(methodName) || "getObject".equals(methodName)
                            || "getObjectStoredProc".equals(methodName)) {
                        Matcher matcher = ResultSetScannerInterceptor.this.regexP.matcher(invocationResult.toString());

                        if (matcher.matches()) {
                            throw new SQLException("value disallowed by filter");
                        }
                    }

                    return invocationResult;
                }
            });

}
项目:openjdk-jdk10    文件:MethodUtil.java   
/**
 * Test if the given class is a proxy class that implements
 * non-public interface.  Such proxy class may be in a non-restricted
 * package that bypasses checkPackageAccess.
 */
private static boolean isNonPublicProxyClass(Class<?> cls) {
    String name = cls.getName();
    int i = name.lastIndexOf('.');
    String pkg = (i != -1) ? name.substring(0, i) : "";
    return Proxy.isProxyClass(cls) && !pkg.startsWith(PROXY_PACKAGE);
}
项目:hadoop    文件:ProtobufRpcEngine.java   
@Override
@SuppressWarnings("unchecked")
public <T> ProtocolProxy<T> getProxy(Class<T> protocol, long clientVersion,
    InetSocketAddress addr, UserGroupInformation ticket, Configuration conf,
    SocketFactory factory, int rpcTimeout, RetryPolicy connectionRetryPolicy,
    AtomicBoolean fallbackToSimpleAuth) throws IOException {

  final Invoker invoker = new Invoker(protocol, addr, ticket, conf, factory,
      rpcTimeout, connectionRetryPolicy, fallbackToSimpleAuth);
  return new ProtocolProxy<T>(protocol, (T) Proxy.newProxyInstance(
      protocol.getClassLoader(), new Class[]{protocol}, invoker), false);
}
项目:spanner-jdbc    文件:CloudSpannerXAConnection.java   
/****
 * XAConnection interface
 ****/

@Override
public ICloudSpannerConnection getConnection() throws SQLException
{
    if (logger.logDebug())
    {
        debug("CloudSpannerXAConnection.getConnection called");
    }

    Connection conn = super.getConnection();

    // When we're outside an XA transaction, autocommit
    // is supposed to be true, per usual JDBC convention.
    // When an XA transaction is in progress, it should be
    // false.
    if (state == STATE_IDLE)
    {
        conn.setAutoCommit(true);
    }

    /*
     * Wrap the connection in a proxy to forbid application from fiddling
     * with transaction state directly during an XA transaction
     */
    ConnectionHandler handler = new ConnectionHandler(conn);
    return (ICloudSpannerConnection) Proxy.newProxyInstance(getClass().getClassLoader(),
            new Class[] { Connection.class, ICloudSpannerConnection.class }, handler);
}