classファイルから対象パッケージ以下のEnumクラスを取得

@param packageName ルートパッケージ名
@param dir 対象ディレクトリ
@return クラスリスト
@throws ClassNotFoundException エラー
@throws IOException
321927
private static Set<Class<?>> findEnumClassesWithFile(final String packageName, final Path dir) {
		Set<Class<?>> classes = new HashSet<>();
		try (Stream<Path> stream = Files.walk(dir)) {
			stream.filter(entry -> entry.getFileName().toString().endsWith(".class")).forEach(file -> {
				StringJoiner joiner = new StringJoiner(".", packageName + ".", "");
				dir.relativize(file).forEach(p -> joiner.add(p.toString()));
				String className = joiner.toString().replaceAll(".class$", "");
				loadEnum(className).ifPresent(classes::add);
			});
		} catch (IOException e) {
			LOG.error(e.getMessage(), e);
		}

		return classes;
	}
697463
public ClassLoader getBundleClassLoader(String packageName, String version) throws ClassNotFoundException
    {
        if ((packageName == null) || (packageName.length() == 0))
            return null;

        ClassLoader classLoader  = null;
        if (this.getClassFinder(null) != null)
        	classLoader = this.getClassFinder(null).findBundleClassLoader(packageName, version);	// Try to find this class in the obr repos

        return classLoader;
    }
365017
public final Package<NotDependsOn> findForbiddenByName(final String packageName) {
        final List<Package<NotDependsOn>> list = getForbidden();
        for (final Package<NotDependsOn> pkg : list) {
            if (pkg.getName().equals(packageName)) {
                return pkg;
            }
        }
        return null;
    }
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;
    }
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;

    }
1114857
public static String convertClassNameToResourcePath(String className) {
        Assert.notNull(className, "Class name must not be null");
        return className.replace(PACKAGE_SEPARATOR, PATH_SEPARATOR);
    }
1355766
public static List<Class<?>> getClassesForPackage(Package pkg, Class classForClassLoader) throws IOException
    {
        return getClassesForPackage(pkg.getName(), classForClassLoader);
    }
894890
public static File getClassFileFromDirectoryInClassPath(String className) {
		String fileName = StringSupport.replaceAll(className, ".", "/");
		fileName += ".class";
		return getFileFromDirectoryInClassPath(fileName, System.getProperty("java.class.path"));
	}
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;
    }
182107
public static Set<String> scanClassNames(final String packageName) throws IOException
	{
		return scanClassNames(packageName, false, true);
	}
1147249
private void parsePackageClasses(String name,
            List<JavaFileObject> files,
            ListBuffer<JCCompilationUnit> trees,
            List<String> excludedPackages)
            throws IOException {
        if (excludedPackages.contains(name)) {
            return;
        }

        docenv.notice("main.Loading_source_files_for_package", name);

        if (files == null) {
            Location location = docenv.fileManager.hasLocation(StandardLocation.SOURCE_PATH)
                    ? StandardLocation.SOURCE_PATH : StandardLocation.CLASS_PATH;
            ListBuffer<JavaFileObject> lb = new ListBuffer<JavaFileObject>();
            for (JavaFileObject fo: docenv.fileManager.list(
                    location, name, EnumSet.of(JavaFileObject.Kind.SOURCE), false)) {
                String binaryName = docenv.fileManager.inferBinaryName(location, fo);
                String simpleName = getSimpleName(binaryName);
                if (isValidClassName(simpleName)) {
                    lb.append(fo);
                }
            }
            files = lb.toList();
        }
        if (files.nonEmpty()) {
            for (JavaFileObject fo : files) {
                parse(fo, trees, false);
            }
        } else {
            messager.warning(Messager.NOPOS, "main.no_source_files_for_package",
                             name.replace(File.separatorChar, '.'));
        }
    }
259099
public static String getPackageName(String className, boolean resource)
    {
        String packageName = null;
        if (className != null)
        {
            if (className.indexOf(File.separator) != -1)
            {
                className = className.substring(0, className.lastIndexOf(File.separator));
                packageName = className.replace(File.separator.charAt(0), '.');
            }
            else if (className.indexOf('/') != -1)
            {
                className = className.substring(0, className.lastIndexOf('/'));
                packageName = className.replace('/', '.');
            }
            else
            {
                if (resource)
                    if (className.endsWith(PROPERTIES))
                        className = className.substring(0, className.length() - PROPERTIES.length());
                if (className.lastIndexOf('.') != -1)
                    packageName = className.substring(0, className.lastIndexOf('.'));
            }
        }
        return packageName;
    }
1146733
public Set<Class<?>> findAndAddClassesInPackageByFile(String packageName, String packagePath,
                                                          final boolean recursive) {
        LOGGER.debug("扫描包{}下、目录{}下的所有class", packageName, packagePath);
        Set<Class<?>> classes = new LinkedHashSet<>();
        // 获取此包的目录 建立一个File
        File dir = new File(packagePath);
        // 如果不存在或者 也不是目录就直接返回
        if (!dir.exists() || !dir.isDirectory()) {
            LOGGER.debug("用户定义包名 " + packageName + " 下没有任何文件");
            return Collections.emptySet();
        }
        // 如果存在 就获取包下的所有文件 包括目录
        File[] dirfiles = dir.listFiles(file -> (recursive && file.isDirectory())
                                                || (file.getName().endsWith("" + "" + ".class")));

        if (dirfiles == null || dirfiles.length == 0) {
            return Collections.emptySet();
        }

        // 循环所有文件
        for (File file : dirfiles) {
            // 如果是目录 则继续扫描
            if (file.isDirectory()) {
                classes.addAll(findAndAddClassesInPackageByFile(packageName + "/" + file.getName(),
                    file.getAbsolutePath(), recursive));
            } else {
                // 如果是java类文件 去掉后面的.class 只留下类名
                String className = file.getName().substring(0, file.getName().length() - 6);
                try {
                    packageName = packageName.replaceAll("/", ".");
                    className = packageName + '.' + className;
                    classes.add(classLoader.loadClass(className));
                } catch (Throwable e) {
                    LOGGER.error("添加用户自定义视图类错误 找不到此类的.class文件", e);
                }
            }
        }
        return classes;
    }
802686
public EnumBuilder withName(String pojoPackage, String className) {
		className = NamingHelper.convertToClassName(className);

		final String fullyQualifiedClassName = pojoPackage + "." + className;
		// Initiate package if necessary
		if (this.pojoPackage == null) {
			withPackage(pojoPackage);
		}
		// Builders should only have 1 active pojo under their responsibility
		if (this.pojo != null) {
			throw new IllegalStateException("Enum already created");
		}

		try {
			// create the class
			logger.debug("Creating Enum " + fullyQualifiedClassName);
			this.pojo = this.pojoModel._class(fullyQualifiedClassName, ClassType.ENUM);

			// Handle Serialization
			// Do enums need to be serializable?
			// implementsSerializable();
		} catch (JClassAlreadyExistsException e) {
			// class already exists - reuse it!
			logger.debug("Enum {} already exists. Reusing it!", fullyQualifiedClassName);
			this.pojo = this.pojoModel._getClass(fullyQualifiedClassName);
		}

		// Add to shortcuts
		this.codeModels.put(fullyQualifiedClassName, this.pojo);
		return this;
	}
469555
public static List<String> getClasses(String... packageNames) {
		List<String> classes = new ArrayList<>();
		for (String packageName : packageNames) {
			String packagePath = packageName.replace('.', '/');
			URL url = Conf.class.getResource("/" + packagePath);
			if (url == null) {
				return classes;
			}
			if (url.getProtocol().equals("jar")) {
				String path = url.getPath();
				int i = path.lastIndexOf('!');
				if (i >= 0) {
					path = path.substring(0, i);
				}
				try (JarFile jar = new JarFile(new File(new URL(path).toURI()))) {
					Enumeration<JarEntry> e = jar.entries();
					while (e.hasMoreElements()) {
						path = e.nextElement().getName();
						if (path.startsWith(packagePath) && path.endsWith(".class")) {
							classes.add(path.substring(0, path.length() - 6).replace('/', '.'));
						}
					}
				} catch (IOException | URISyntaxException e) {
					throw new RuntimeException(e);
				}
			} else {
				try {
					String root = new File(url.toURI()).getPath();
					root = root.substring(0, root.length() - packagePath.length());
					search(classes, root, packagePath);
				} catch (URISyntaxException e) {
					throw new RuntimeException(e);
				}
			}
		}
		return classes;
	}
760538
public static String packageNameOf(Class<?> clazz) {
        String name = clazz.getName();
        int pos = name.lastIndexOf('.');
        E.unexpectedIf(pos < 0, "Class does not have package: " + name);
        return name.substring(0, pos);
    }