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.
979435
public static boolean isNonPublicProxyClass(Class<?> cls) {
        String name = cls.getName();
        int i = name.lastIndexOf('.');
        String pkg = (i != -1) ? name.substring(0, i) : "";

        // NOTE: Android creates proxies in the "default" package (and not com.sun.proxy), which
        // makes this check imprecise. However, this function is only ever called if there's
        // a security manager installed (which is the never case on android).
        return Proxy.isProxyClass(cls) && !pkg.isEmpty();
    }
1301864
private static boolean isBundledInJre(String className) {
    if (className.startsWith("javax.accessibility.")
        || className.startsWith("javax.activation.")
        || className.startsWith("javax.activity.")
        || className.startsWith("javax.annotation.")
        || className.startsWith("javax.crypto.")
        || className.startsWith("javax.imageio.")
        || className.startsWith("javax.jws.")
        || className.startsWith("javax.lang.model.")
        || className.startsWith("javax.management.")
        || className.startsWith("javax.naming.")
        || className.startsWith("javax.net.")
        || className.startsWith("javax.print.")
        || className.startsWith("javax.rmi.")
        || className.startsWith("javax.script.")
        || className.startsWith("javax.security.")
        || className.startsWith("javax.sound.")
        || className.startsWith("javax.sql.")
        || className.startsWith("javax.swing.")
        || className.startsWith("javax.tools.")
        || className.startsWith("javax.transaction.")
        || className.startsWith("javax.xml.")) {
      return true;
    }
    return false;
  }
1234802
private static boolean getInternalPublicMethods(Class<?> cls,
                                                    Map<Signature, Method> sigs) {
        Method[] methods = null;
        try {
            /*
             * This class or interface is non-public so we
             * can't use any of it's methods. Go back and
             * try again with a superclass or superinterface.
             */
            if (!Modifier.isPublic(cls.getModifiers())) {
                return false;
            }
            if (!ReflectUtil.isPackageAccessible(cls)) {
                return false;
            }

            methods = cls.getMethods();
        } catch (SecurityException se) {
            return false;
        }

        /*
         * Check for inherited methods with non-public
         * declaring classes. They might override and hide
         * methods from their superclasses or
         * superinterfaces.
         */
        boolean done = true;
        for (int i=0; i < methods.length; i++) {
            Class<?> dc = methods[i].getDeclaringClass();
            if (!Modifier.isPublic(dc.getModifiers())) {
                done = false;
                break;
            }
        }

        if (done) {
            /*
             * We're done. Spray all the methods into
             * the list and then we're out of here.
             */
            for (int i=0; i < methods.length; i++) {
                addMethod(sigs, methods[i]);
            }
        } else {
            /*
             * Simulate cls.getDeclaredMethods() by
             * stripping away inherited methods.
             */
            for (int i=0; i < methods.length; i++) {
                Class<?> dc = methods[i].getDeclaringClass();
                if (cls.equals(dc)) {
                    addMethod(sigs, methods[i]);
                }
            }
        }
        return done;
    }
288624
public static <T extends Annotation> MethodInvokeProxy proxyByAnnotation(Object target,Class<T> annotationClass,Object ...args)
	{
		Method m=findMethodByAnnotation(target,annotationClass);
		if(m!=null)
		{
			return new MethodInvokeProxy(target, m, args);
		}
		return null;
	}
1021207
public static boolean isProxy(GSIConstants.CertificateType certType) {
        return isGsi2Proxy(certType) || isGsi3Proxy(certType) || isGsi4Proxy(certType);
    }
621056
private static Class<?> getProxyClass0(ClassLoader loader,
                                           Class<?>... interfaces) {
        if (interfaces.length > 65535) {
            throw new IllegalArgumentException("interface limit exceeded");
        }

        Class<?> proxyClass = null;

        /* collect interface names to use as key for proxy class cache */
        String[] interfaceNames = new String[interfaces.length];

        // for detecting duplicates
        Set<Class<?>> interfaceSet = new HashSet<>();

        for (int i = 0; i < interfaces.length; i++) {
            /*
             * Verify that the class loader resolves the name of this
             * interface to the same Class object.
             */
            String interfaceName = interfaces[i].getName();
            Class<?> interfaceClass = null;
            try {
                interfaceClass = Class.forName(interfaceName, false, loader);
            } catch (ClassNotFoundException e) {
            }
            if (interfaceClass != interfaces[i]) {
                throw new IllegalArgumentException(
                    interfaces[i] + " is not visible from class loader");
            }

            /*
             * Verify that the Class object actually represents an
             * interface.
             */
            if (!interfaceClass.isInterface()) {
                throw new IllegalArgumentException(
                    interfaceClass.getName() + " is not an interface");
            }

            /*
             * Verify that this interface is not a duplicate.
             */
            if (interfaceSet.contains(interfaceClass)) {
                throw new IllegalArgumentException(
                    "repeated interface: " + interfaceClass.getName());
            }
            interfaceSet.add(interfaceClass);

            interfaceNames[i] = interfaceName;
        }

        /*
         * Using string representations of the proxy interfaces as
         * keys in the proxy class cache (instead of their Class
         * objects) is sufficient because we require the proxy
         * interfaces to be resolvable by name through the supplied
         * class loader, and it has the advantage that using a string
         * representation of a class makes for an implicit weak
         * reference to the class.
         */
        List<String> key = Arrays.asList(interfaceNames);

        /*
         * Find or create the proxy class cache for the class loader.
         */
        Map<List<String>, Object> cache;
        synchronized (loaderToCache) {
            cache = loaderToCache.get(loader);
            if (cache == null) {
                cache = new HashMap<>();
                loaderToCache.put(loader, cache);
            }
            /*
             * This mapping will remain valid for the duration of this
             * method, without further synchronization, because the mapping
             * will only be removed if the class loader becomes unreachable.
             */
        }

        /*
         * Look up the list of interfaces in the proxy class cache using
         * the key.  This lookup will result in one of three possible
         * kinds of values:
         *     null, if there is currently no proxy class for the list of
         *         interfaces in the class loader,
         *     the pendingGenerationMarker object, if a proxy class for the
         *         list of interfaces is currently being generated,
         *     or a weak reference to a Class object, if a proxy class for
         *         the list of interfaces has already been generated.
         */
        synchronized (cache) {
            /*
             * Note that we need not worry about reaping the cache for
             * entries with cleared weak references because if a proxy class
             * has been garbage collected, its class loader will have been
             * garbage collected as well, so the entire cache will be reaped
             * from the loaderToCache map.
             */
            do {
                Object value = cache.get(key);
                if (value instanceof Reference) {
                    proxyClass = (Class<?>) ((Reference<?>) value).get();
                }
                if (proxyClass != null) {
                    // proxy class already generated: return it
                    return proxyClass;
                } else if (value == pendingGenerationMarker) {
                    // proxy class being generated: wait for it
                    try {
                        cache.wait();
                    } catch (InterruptedException e) {
                        /*
                         * The class generation that we are waiting for should
                         * take a small, bounded time, so we can safely ignore
                         * thread interrupts here.
                         */
                    }
                    continue;
                } else {
                    /*
                     * No proxy class for this list of interfaces has been
                     * generated or is being generated, so we will go and
                     * generate it now.  Mark it as pending generation.
                     */
                    cache.put(key, pendingGenerationMarker);
                    break;
                }
            } while (true);
        }

        try {
            String proxyPkg = null;     // package to define proxy class in

            /*
             * Record the package of a non-public proxy interface so that the
             * proxy class will be defined in the same package.  Verify that
             * all non-public proxy interfaces are in the same package.
             */
            for (int i = 0; i < interfaces.length; i++) {
                int flags = interfaces[i].getModifiers();
                if (!Modifier.isPublic(flags)) {
                    String name = interfaces[i].getName();
                    int n = name.lastIndexOf('.');
                    String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
                    if (proxyPkg == null) {
                        proxyPkg = pkg;
                    } else if (!pkg.equals(proxyPkg)) {
                        throw new IllegalArgumentException(
                            "non-public interfaces from different packages");
                    }
                }
            }

            if (proxyPkg == null) {
                // if no non-public proxy interfaces, use the default package.
                proxyPkg = "";
            }

            {
                // Android-changed: Generate the proxy directly instead of calling
                // through to ProxyGenerator.
                /* J2ObjC removed.
                List<Method> methods = getMethods(interfaces);
                Collections.sort(methods, ORDER_BY_SIGNATURE_AND_SUBTYPE);
                validateReturnTypes(methods);
                List<Class<?>[]> exceptions = deduplicateAndGetExceptions(methods);

                Method[] methodsArray = methods.toArray(new Method[methods.size()]);
                Class<?>[][] exceptionsArray = exceptions.toArray(new Class<?>[exceptions.size()][]);
                */

                /*
                 * Choose a name for the proxy class to generate.
                 */
                final long num;
                synchronized (nextUniqueNumberLock) {
                    num = nextUniqueNumber++;
                }
                String proxyName = proxyPkg + proxyClassNamePrefix + num;

                proxyClass = generateProxy(proxyName, interfaces, loader);
            }
            // add to set of all generated proxy classes, for isProxyClass
            proxyClasses.put(proxyClass, null);

        } finally {
            /*
             * We must clean up the "pending generation" state of the proxy
             * class cache entry somehow.  If a proxy class was successfully
             * generated, store it in the cache (with a weak reference);
             * otherwise, remove the reserved entry.  In all cases, notify
             * all waiters on reserved entries in this cache.
             */
            synchronized (cache) {
                if (proxyClass != null) {
                    cache.put(key, new WeakReference<Class<?>>(proxyClass));
                } else {
                    cache.remove(key);
                }
                cache.notifyAll();
            }
        }
        return proxyClass;
    }
71777
@Override
    protected Class<?> resolveProxyClass(String[] interfaceNames) throws ClassNotFoundException {
        ClassLoader proxyClassLoader = classLoader;
        Class<?>[] interfaces = new Class[interfaceNames.length];
        Class<?> nonPublicInterface = null;

        for (int i = 0; i < interfaceNames.length; i++) {
            Class<?> intf = loadClass(interfaceNames[i]);

            if (!Modifier.isPublic(intf.getModifiers())) {
                ClassLoader classLoader = getClassLoader(intf);
                if (nonPublicInterface != null) {
                    if (classLoader != proxyClassLoader) {
                        throw new IllegalAccessError(nonPublicInterface + " and " + intf + " both declared non-public in different class loaders");
                    }
                } else {
                    nonPublicInterface = intf;
                    proxyClassLoader = classLoader;
                }
            }

            interfaces[i] = intf;
        }

        try {
            return Proxy.getProxyClass(proxyClassLoader, interfaces);
        } catch (IllegalArgumentException ex) {
            throw new ClassNotFoundException(null, ex);
        }
    }
902971
public static boolean isClassVetoed(Class<?> type) {
        if (type.isAnnotationPresent(Vetoed.class)) {
            return true;
        }
        return isPackageVetoed(type.getPackage());
    }
922953
private int checkClass(final ClassReader reader, Pattern suppressAnnotationsPattern) throws ForbiddenApiException {
    final String className = Type.getObjectType(reader.getClassName()).getClassName();
    final ClassScanner scanner = new ClassScanner(this, forbiddenSignatures, suppressAnnotationsPattern); 
    try {
      reader.accept(scanner, ClassReader.SKIP_FRAMES);
    } catch (RelatedClassLoadingException rcle) {
      final Exception cause = rcle.getException();
      final StringBuilder msg = new StringBuilder()
          .append("Check for forbidden API calls failed while scanning class '")
          .append(className)
          .append('\'');
      final String source = scanner.getSourceFile();
      if (source != null) {
        msg.append(" (").append(source).append(')');
      }
      msg.append(": ").append(cause);
      msg.append(" (while looking up details about referenced class '").append(rcle.getClassName()).append("')");
      assert cause != null && (cause instanceof IOException || cause instanceof ClassNotFoundException);
      throw new ForbiddenApiException(msg.toString(), cause);
    }
    final List<ForbiddenViolation> violations = scanner.getSortedViolations();
    final Pattern splitter = Pattern.compile(Pattern.quote(ForbiddenViolation.SEPARATOR));
    for (final ForbiddenViolation v : violations) {
      for (final String line : splitter.split(v.format(className, scanner.getSourceFile()))) {
        logger.error(line);
      }
    }
    return violations.size();
  }
1348817
private Class getDynamicProxyClass(Class baseClass) {
        Class[] m_dynamicProxyClassInterfaces;
        if (foundInterfaces.containsKey(baseClass)) {
            m_dynamicProxyClassInterfaces = (Class[])foundInterfaces.get(baseClass);
        } else {
            m_dynamicProxyClassInterfaces = getInterfaces(baseClass);
            foundInterfaces.put(baseClass, m_dynamicProxyClassInterfaces);
        }

        // return dynymic Proxy Class implementing all interfaces
        Class proxyClazz = Proxy.getProxyClass(baseClass.getClassLoader(), m_dynamicProxyClassInterfaces);
        return proxyClazz;
    }
853187
public Class<?> getRealClass(Class proxy) {
		try {
			return Class.forName(getRealClassname(proxy.getName()));
		} catch (ClassNotFoundException ex) {
		}
		return proxy;
	}
201875
private boolean isProxied(HttpServletRequest httpServletRequest) {
        if (Proxy.isProxyClass(httpServletRequest.getClass())) {
            InvocationHandler handler = Proxy.getInvocationHandler(httpServletRequest);
            return handler instanceof ServletRequestInvocationHandler;
        }
        return false;
    }
66208
@SuppressWarnings("unchecked")
    public <P> P as(final Class<P> proxyType) {
        final boolean isMap = (object instanceof Map);
        final InvocationHandler handler = new InvocationHandler() {
            @Override
            @SuppressWarnings("null")
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String name = method.getName();

                // Actual method name matches always come first
                try {
                    return on(type, object).call(name, args).get();
                }

                // [#14] Emulate POJO behaviour on wrapped map objects
                catch (ReflectException e) {
                    if (isMap) {
                        Map<String, Object> map = (Map<String, Object>) object;
                        int length = (args == null ? 0 : args.length);

                        if (length == 0 && name.startsWith("get")) {
                            return map.get(property(name.substring(3)));
                        }
                        else if (length == 0 && name.startsWith("is")) {
                            return map.get(property(name.substring(2)));
                        }
                        else if (length == 1 && name.startsWith("set")) {
                            map.put(property(name.substring(3)), args[0]);
                            return null;
                        }
                    }

























                    throw e;
                }
            }
        };

        return (P) Proxy.newProxyInstance(proxyType.getClassLoader(), new Class[] { proxyType }, handler);
    }
301385
View build() throws IOException {
        final Class<? extends T> proxyClass = generateProxyClass();
        if (proxyClass == null) {
            return null;
        }

        final Constructor<? extends T> constructor = getProxyClassConstructor(proxyClass);

        final View result;
        try {
            result = constructor.newInstance(CONSTRUCTOR_ARG_VALUES);
        } catch (InstantiationException e) {
            // Should not be thrown, generated class is not abstract.
            throw new AssertionError(e);
        } catch (IllegalAccessException e) {
            // Should not be thrown, the generated constructor is accessible.
            throw new AssertionError(e);
        } catch (InvocationTargetException e) {
            // Thrown when the base class constructor throws an exception.
            throw launderCause(e);
        }

        ((ViewProxy) result).setInterceptor(mInterceptor);
        return result;
    }
109338
<T> T createProxy(Class<T> interfaceClass, C adsServiceClient) {
    Set<Class<?>> interfaces = Sets.newHashSet(adsServiceClient.getClass().getInterfaces());
    interfaces.add(interfaceClass);
    Object proxy = Proxy.newProxyInstance(
        adsServiceClient.getSoapClient().getClass().getClassLoader(),
        interfaces.toArray(new Class[] {}), adsServiceClient);
    return interfaceClass.cast(proxy);
  }
931691
public static boolean isVetoed(Class<?> javaClass) {
        if (javaClass.isAnnotationPresent(Vetoed.class)) {
            return true;
        }
        return isPackageVetoed(javaClass.getPackage());
    }
1232564
@SuppressWarnings("unchecked")
  public static <T> Class<T> deProxy(Class<?> type) {
    // Ignore JDK proxies
    if (type.isInterface())
      return (Class<T>) type;

    if (isProxied(type)) {
      final Class<?> superclass = type.getSuperclass();
      if (!superclass.equals(Object.class) && !superclass.equals(Proxy.class))
        return (Class<T>) superclass;
      else {
        Class<?>[] interfaces = type.getInterfaces();
        if (interfaces.length > 0)
          return (Class<T>) interfaces[0];
      }
    }

    return (Class<T>) type;
  }