Get class by condition

@param packageName
@param packagePath
@param parent
@param annotation
@param recursive
@return
548075
private Set<ClassInfo> findClassByPackage(final String packageName, final String packagePath,
                                              final Class<?> parent, final Class<? extends Annotation> annotation,
                                              final boolean recursive, Set<ClassInfo> classes) throws ClassNotFoundException {

        // Get the directory of this package to create a File
        File dir = new File(packagePath);
        // If not exist or is not a direct return to the directory
        if ((!dir.exists()) || (!dir.isDirectory())) {
            log.warn("The package [{}] not found.", packageName);
        }
        // If present, get all the files under the package include the directory
        File[] dirFiles = accept(dir, recursive);
        // Loop all files
        if (null != dirFiles && dirFiles.length > 0) {
            for (File file : dirFiles) {
                // If it is a directory, continue scanning
                if (file.isDirectory()) {
                    findClassByPackage(packageName + '.' + file.getName(), file.getAbsolutePath(), parent, annotation, recursive, classes);
                } else {
                    // If the java class file is removed later. Class only leave the class name
                    String   className = file.getName().substring(0, file.getName().length() - 6);
                    Class<?> clazz     = Class.forName(packageName + '.' + className);
                    if (null != parent && null != annotation) {
                        if (null != clazz.getSuperclass() && clazz.getSuperclass().equals(parent) &&
                                null != clazz.getAnnotation(annotation)) {
                            classes.add(new ClassInfo(clazz));
                        }
                        continue;
                    }
                    if (null != parent) {
                        if (null != clazz.getSuperclass() && clazz.getSuperclass().equals(parent)) {
                            classes.add(new ClassInfo(clazz));
                        } else {
                            if (null != clazz.getInterfaces() && clazz.getInterfaces().length > 0 && clazz.getInterfaces()[0].equals(parent)) {
                                classes.add(new ClassInfo(clazz));
                            }
                        }
                        continue;
                    }
                    if (null != annotation) {
                        if (null != clazz.getAnnotation(annotation)) {
                            classes.add(new ClassInfo(clazz));
                        }
                        continue;
                    }
                    classes.add(new ClassInfo(clazz));
                }
            }
        }
        return classes;
    }
50654
private static Class resolveRClass(String packageName) {
        do {
            try {
                return Class.forName(packageName + ".R$string");
            } catch (ClassNotFoundException e) {
                packageName = packageName.contains(".") ? packageName.substring(0, packageName.lastIndexOf('.')) : "";
            }
        } while (!TextUtils.isEmpty(packageName));

        return null;
    }
805394
@Nullable
  public static String getClassPackageName (@Nullable final Class <?> aClass)
  {
    return aClass == null ? null : getClassPackageName (aClass.getName ());
  }
697834
protected Class findClassInternal(String name)
        throws ClassNotFoundException {

        if (!validate(name))
            throw new ClassNotFoundException(name);

        String tempPath = name.replace('.', '/');
        String classPath = tempPath + ".class";

        ResourceEntry entry = null;

        entry = findResourceInternal(name, classPath);

        if (entry == null)
            throw new ClassNotFoundException(name);

        Class clazz = entry.loadedClass;
        if (clazz != null)
            return clazz;

        synchronized (this) {
            if (entry.binaryContent == null && entry.loadedClass == null)
                throw new ClassNotFoundException(name);

            // Looking up the package
            String packageName = null;
            int pos = name.lastIndexOf('.');
            if (pos != -1)
                packageName = name.substring(0, pos);
        
            Package pkg = null;
        
            if (packageName != null) {
                pkg = getPackage(packageName);
                // Define the package (if null)
                if (pkg == null) {
                    try {
                        if (entry.manifest == null) {
                            definePackage(packageName, null, null, null, null,
                                    null, null, null);
                        } else {
                            definePackage(packageName, entry.manifest,
                                    entry.codeBase);
                        }
                    } catch (IllegalArgumentException e) {
                        // Ignore: normal error due to dual definition of package
                    }
                    pkg = getPackage(packageName);
                }
            }
    
            if (securityManager != null) {

                // Checking sealing
                if (pkg != null) {
                    boolean sealCheck = true;
                    if (pkg.isSealed()) {
                        sealCheck = pkg.isSealed(entry.codeBase);
                    } else {
                        sealCheck = (entry.manifest == null)
                            || !isPackageSealed(packageName, entry.manifest);
                    }
                    if (!sealCheck)
                        throw new SecurityException
                            ("Sealing violation loading " + name + " : Package "
                             + packageName + " is sealed.");
                }
    
            }

            if (entry.loadedClass == null) {
                clazz = defineClass(name, entry.binaryContent, 0,
                        entry.binaryContent.length, 
                        new CodeSource(entry.codeBase, entry.certificates));
                entry.loadedClass = clazz;
                entry.binaryContent = null;
                entry.source = null;
                entry.codeBase = null;
                entry.manifest = null;
                entry.certificates = null;
            } else {
                clazz = entry.loadedClass;
            }
        }
        
        return clazz;

    }
319176
private void definePackageForFindClass(final String name, final String packageName) {
        try {
            AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                @Override
                public Object run() {
                    String path = name.replace('.', '/').concat(".class");
                    for (URL url : getURLs()) {
                        try {
                            if (url.getContent() instanceof JarFile) {
                                JarFile jarFile = (JarFile) url.getContent();
                                // Check the jar entry data before needlessly creating the
                                // manifest
                                if (jarFile.getJarEntryData(path) != null
                                        && jarFile.getManifest() != null) {
                                    definePackage(packageName, jarFile.getManifest(),
                                            url);
                                    return null;
                                }

                            }
                        } catch (IOException ex) {
                            // Ignore
                        }
                    }
                    return null;
                }
            }, AccessController.getContext());
        } catch (java.security.PrivilegedActionException ex) {
            // Ignore
        }
    }
38504
public static Class getGenericClassFromParent(Object parent) {
		return (Class) ((ParameterizedType) parent.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}
873766
def getClassInPackageFromName(className, pkg):
    
    # TODO: more efficiency!
    n = getAvClassNamesInPackage(pkg)
    i = n.index(className)
    c = getAvailableClassesInPackage(pkg)
    return c[i]
1325081
public static SortedSet<String> getClassesForPackage(Package pkg, ClassLoader classLoader) {
        SortedSet<String> classes = new TreeSet<>(new Comparator<String>() {
           public int compare(String o1, String o2) {
              String simpleName1 = getSimpleName(o1);
              String simpleName2 = getSimpleName(o2);
              return simpleName1.compareTo(simpleName2);
           }

           private String getSimpleName(String className) {
              return className.substring(className.lastIndexOf('.'));
           }
        });

        String pkgname = pkg.getName();
        String relPath = pkgname.replace('.', '/');

        // Get a File object for the package
        Enumeration<URL> resources;
        try {
            resources = classLoader.getResources(relPath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        while(resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            if (resource.toString().startsWith("jar:")) {
                processJarfile(resource, pkgname, classes);
            } else {
                processDirectory(new File(resource.getPath()), pkgname, classes);
            }
        }

        return classes;
    }
657823
private void definePackageIfNecessary(String className) {
		int lastDot = className.lastIndexOf('.');
		if (lastDot >= 0) {
			String packageName = className.substring(0, lastDot);
			if (getPackage(packageName) == null) {
				try {
					definePackage(className, packageName);
				}
				catch (IllegalArgumentException ex) {
					// Tolerate race condition due to being parallel capable
					if (getPackage(packageName) == null) {
						// This should never happen as the IllegalArgumentException
						// indicates that the package has already been defined and,
						// therefore, getPackage(name) should not have returned null.
						throw new AssertionError(
								"Package " + packageName + " has already been defined "
										+ "but it could not be found");
					}
				}
			}
		}
	}
961383
@Requires({
    "parent != null",
    "annotation != null"
  })
  @Ensures("result != null")
  @SuppressWarnings("unchecked")
  protected List<Long> getLineNumbers(Element parent,
                                      AnnotationMirror annotation) {
    if (JavaUtils.classExists("com.sun.source.util.Trees")) {
      try {
        return (List<Long>) Class
            .forName("com.google.java.contract.core.apt.JavacUtils")
            .getMethod("getLineNumbers", ProcessingEnvironment.class,
                       Element.class, AnnotationMirror.class)
            .invoke(null, utils.processingEnv, parent, annotation);
      } catch (Exception e) {
        return Collections.emptyList();
      }
    } else {
      return Collections.emptyList();
    }
  }
539008
private void obtainClassInfoRecursive(final Set<ClassInfo> reachableClassInfo) {
        reachableClassInfo.addAll(memberClassNameToClassInfo.values());
        for (final PackageInfo subPackageInfo : getChildren()) {
            subPackageInfo.obtainClassInfoRecursive(reachableClassInfo);
        }
    }
611954
public static void infoOnGeneratedClasses(Class<? extends Annotation> annotation, String packageName, String className) {
		String msg = String.format("class '%s' in package '%s' is generated by '@%s' annotation processor", className, packageName, annotation.getSimpleName());
		
		printMessage(msg);
	}
942540
@Override
    public Stream<Class> scan(String annotation, String pkg) {
        if (pkg == null) {
            return Stream.empty();
        }
        List<Class> classes = doScan(annotation, pkg);
        return classes.stream();
    }
440615
public static List<String> getAllClassesInPackage(String packageName) {
		List<String> classesNames = new Vector<>();
		// create scanner and disable default filters (that is the 'false' argument)
		final ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
		// add include filters which matches all the classes (or use your own)
		provider.addIncludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*")));

		// get matching classes defined in the package
		final Set<BeanDefinition> classes = provider.findCandidateComponents(packageName);

		// this is how you can load the class type from BeanDefinition instance
		for (BeanDefinition bean : classes) {
			classesNames.add(bean.getBeanClassName());
		}
		return classesNames;
	}
1194339
public Set<Class<?>> findAndAddClassesInPackageByFile(JarFile jar, String packageDirName,
                                                          String packageName, boolean recursive) {
        LOGGER.debug("尝试扫描jar文件{}");
        Set<Class<?>> classes = new LinkedHashSet<>();
        LOGGER.debug("jar类型的扫描");
        // 获取jar
        // 从此jar包 得到一个枚举类
        Enumeration<JarEntry> entries = jar.entries();
        // 同样的进行循环迭代
        while (entries.hasMoreElements()) {
            // 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件
            JarEntry entry = entries.nextElement();
            String name = entry.getName();
            // 如果是以/开头的
            if (name.charAt(0) == '/') {
                // 获取后面的字符串
                name = name.substring(1);
            }
            // 如果前半部分和定义的包名相同
            if (name.startsWith(packageDirName)) {
                int idx = name.lastIndexOf('/');
                // 如果以"/"结尾 是一个包
                if (idx != -1) {
                    // 获取包名 把"/"替换成"."
                    packageName = name.substring(0, idx).replace('/', '.');
                }
                // 如果可以迭代下去 并且是一个包
                if ((idx != -1) || recursive) {
                    // 如果是一个.class文件 而且不是目录
                    if (name.endsWith(".class") && !entry.isDirectory()) {
                        // 去掉后面的".class" 获取真正的类名
                        String className = name.substring(packageName.length() + 1,
                            name.length() - 6);
                        className = packageName + "." + className;
                        try {
                            LOGGER.debug("尝试构建class：{}", className);
                            // 添加到classes
                            classes.add(classLoader.loadClass(className));
                        } catch (Throwable e) {
                            LOGGER.warn("找不到{}文件", className + ".class", e);
                        }
                    }
                }
            }
        }

        return classes;
    }
295889
@Override
    protected Class<?> findClass(final String className)
            throws ClassNotFoundException, LinkageError, SecurityException {
        final Class<?> loadedClass = findLoadedClass(className);
        if (loadedClass != null) {
            return loadedClass;
        }

        // Get ClassInfo for named class
        final ClassInfo classInfo = scanResult.getClassInfo(className);

        // Try environment classloaders first
        boolean triedClassInfoLoader = false;
        final ClassLoader[] classLoaderOrder = scanResult.getClassLoaderOrderRespectingParentDelegation();
        if (classLoaderOrder != null) {
            // Try environment classloaders
            for (final ClassLoader envClassLoader : classLoaderOrder) {
                try {
                    return Class.forName(className, scanResult.scanSpec.initializeLoadedClasses, envClassLoader);
                } catch (ReflectiveOperationException | LinkageError e) {
                    // Ignore
                }
                if (classInfo != null && envClassLoader == classInfo.classLoader) {
                    triedClassInfoLoader = true;
                }
            }
        }

        // Try specific classloader for the classpath element that the classfile was obtained from
        if (!triedClassInfoLoader && classInfo != null && classInfo.classLoader != null) {
            try {
                return Class.forName(className, scanResult.scanSpec.initializeLoadedClasses, classInfo.classLoader);
            } catch (final ReflectiveOperationException | LinkageError e) {
                // Ignore
            }
        }

        // If class came from a module, and it was not able to be loaded by the environment classloader,
        // then it is possible it was a non-public class, and ClassGraph found it by ignoring class visibility
        // when reading the resources in exported packages directly. Force ClassGraph to respect JPMS
        // encapsulation rules by refusing to load modular classes that the context/system classloaders
        // could not load. (A SecurityException should be thrown above, but this is here for completeness.)
        if (classInfo != null && classInfo.classpathElement instanceof ClasspathElementModule
                && !classInfo.isPublic()) {
            throw new ClassNotFoundException("Classfile for class " + className + " was found in a module, "
                    + "but the context and system classloaders could not load the class, probably because "
                    + "the class is not public.");
        }

        // Try obtaining the classfile as a resource, and defining the class from the resource content
        final ResourceList classfileResources = scanResult
                .getResourcesWithPath(JarUtils.classNameToClassfilePath(className));
        if (classfileResources != null) {
            for (final Resource resource : classfileResources) {
                // Iterate through resources (only loading of first resource in the list will be attempted)
                try {
                    // Load the content of the resource, and define a class from it
                    final ByteBuffer resourceByteBuffer = resource.read();
                    return defineClass(className, resourceByteBuffer, null);
                } catch (final IOException e) {
                    throw new ClassNotFoundException("Could not load classfile for class " + className + " : " + e);
                } finally {
                    resource.close();
                }
            }
        }
        throw new ClassNotFoundException("Could not load classfile for class " + className);
    }
1268403
public Class getClassByName(String name)
	{

		if (name.indexOf(".") != -1)
		{
			try
			{
				return Class.forName(name,true,gt.getClassLoader());
			}
			catch (ClassNotFoundException e)
			{
				return null;
			}

		}
		else
		{
			Class cls = map.get(name);
			if (cls == null)
			{
				for (String pkg : pkgList)
				{
					try
					{
						String clsName = pkg.concat(name);
						cls = Class.forName(clsName,true,gt.getClassLoader());
						map.put(name, cls);
						return cls;

					}
					catch (Exception ex)
					{
						// continue;
					}
				}
				return null;
			}
			else
			{
				return cls;
			}

		}

	}