Refine search
/** * Gets checkstyle's modules (directly, not recursively) in the given packages. * @param packages the collection of package names to use * @param loader the class loader used to load Checkstyle package names * @return the set of checkstyle's module classes * @throws IOException if the attempt to read class path resources failed * @see #isCheckstyleModule(Class) */ public static Set<Class<?>> getCheckstyleModules( Collection<String> packages, ClassLoader loader) throws IOException { final ClassPath classPath = ClassPath.from(loader); return packages.stream() .flatMap(pkg -> classPath.getTopLevelClasses(pkg).stream()) .map(ClassPath.ClassInfo::load) .filter(ModuleReflectionUtil::isCheckstyleModule) .collect(Collectors.toSet()); }
/** * Gets checkstyle's modules in the given package recursively. * @param packageName the package name to use * @param loader the class loader used to load Checkstyle package name * @return the set of checkstyle's module classes * @throws IOException if the attempt to read class path resources failed * @see ModuleReflectionUtil#isCheckstyleModule(Class) */ private static Set<Class<?>> getCheckstyleModulesRecursive( String packageName, ClassLoader loader) throws IOException { final ClassPath classPath = ClassPath.from(loader); return classPath.getTopLevelClassesRecursive(packageName).stream() .map(ClassPath.ClassInfo::load) .filter(ModuleReflectionUtil::isCheckstyleModule) .filter(cls -> !cls.getCanonicalName() .startsWith("com.puppycrawl.tools.checkstyle.internal.testmodules")) .filter(cls -> !cls.getCanonicalName() .startsWith("com.puppycrawl.tools.checkstyle.packageobjectfactory")) .collect(Collectors.toSet()); }
ClassInfo(String resourceName, ClassLoader loader) { super(resourceName, loader); this.className = getClassName(resourceName); }
private List<Class<?>> loadClassesInPackage() throws IOException { List<Class<?>> classes = Lists.newArrayList(); String packageName = getClass().getPackage().getName(); for (ClassPath.ClassInfo classInfo : ClassPath.from(getClass().getClassLoader()).getTopLevelClasses(packageName)) { Class<?> cls; try { cls = classInfo.load(); } catch (NoClassDefFoundError e) { // In case there were linking problems, this is probably not a class we care to test anyway. logger.log(Level.SEVERE, "Cannot load class " + classInfo + ", skipping...", e); continue; } if (!cls.isInterface()) { classes.add(cls); } } return classes; }
try { ImmutableSet<ClassInfo> pluginPackageSubclasses = ClassPath .from(Thread.currentThread().getContextClassLoader()) .getTopLevelClassesRecursive(PLUGIN_PACKAGE_NAME); boolean classNameEndWithPluginSuffix = classInfo.getName().endsWith(PLUGIN_CLASS_SUFFIX); Class<?> pluginClass = classInfo.load();
/** Returns all top level classes whose package name is {@code packageName}. */ public ImmutableSet<ClassInfo> getTopLevelClasses(String packageName) { checkNotNull(packageName); ImmutableSet.Builder<ClassInfo> builder = ImmutableSet.builder(); for (ClassInfo classInfo : getTopLevelClasses()) { if (classInfo.getPackageName().equals(packageName)) { builder.add(classInfo); } } return builder.build(); }
@Test public void eachSubValidatorIsRegistered() throws Exception { // Load sub-classes of SubValidator that live within the same package as top-level classes. ImmutableSet<Class<?>> existingSubValidators = ClassPath.from(SubValidator.class.getClassLoader()) .getTopLevelClasses(Reflection.getPackageName(SubValidator.class)) .stream() .map(ClassInfo::load) .filter(clazz -> isConcreteSubValidator(clazz)) .collect(toImmutableSet()); ImmutableSet<Class<?>> registeredSubValidators = ImmutableSet.<Class<?>>builder() .addAll(toClasses(AppBundleValidator.BUNDLE_FILE_SUB_VALIDATORS)) .addAll(toClasses(AppBundleValidator.BUNDLE_SUB_VALIDATORS)) .addAll(toClasses(BundleModulesValidator.MODULE_FILE_SUB_VALIDATORS)) .addAll(toClasses(BundleModulesValidator.MODULES_SUB_VALIDATORS)) .build(); assertThat(existingSubValidators).containsExactlyElementsIn(registeredSubValidators); }
private static List<Class> getClasses(String packageName) throws ClassNotFoundException, IOException { List<Class> classes = new ArrayList<>(); ClassPath classpath = ClassPath.from(AbstractModelTest.class.getClassLoader()); String packagePrefix = packageName + '.'; ImmutableSet.Builder<ClassPath.ClassInfo> builder = ImmutableSet.builder(); classpath.getAllClasses().stream().filter(classInfo -> classInfo.getName().startsWith(packagePrefix)).forEach(builder::add); ImmutableSet<ClassPath.ClassInfo> packageClasses = builder.build(); classes.addAll(packageClasses.stream().map(ClassPath.ClassInfo::load).collect(Collectors.toList())); return classes; }
/** * This is really only useful for unit tests, do not call otherwise */ public static void scanEntities(String packageName) throws IOException, ClassNotFoundException { ImmutableSet<ClassInfo> classes = ClassPath.from(TestUtil.class.getClassLoader()).getTopLevelClasses(packageName); Set<String> names = new HashSet<String>(); if (classes.size() <= 1) { throw new InternalErrorException("Found no classes"); } for (ClassInfo classInfo : classes) { Class<?> clazz = Class.forName(classInfo.getName()); Entity entity = clazz.getAnnotation(Entity.class); if (entity == null) { continue; } scanClass(names, clazz, false); } }
classPath = ClassPath.from(loader); } catch (IOException e) { return null; ImmutableSet<ClassInfo> classSet = classPath.getTopLevelClassesRecursive(packageName); Set<Class<?>> classes = new HashSet<>(classSet.size()); Class<?> aClass = classInfo.load();
public static void unpackDummyResources(String prefix, Path output) throws IOException { ClassPath classPath = ClassPath.from(TestData.class.getClassLoader()); Map<String, URL> files = classPath.getResources().stream() .filter(info -> info.getResourceName().startsWith(prefix)) .collect(Collectors.toMap( info -> info.getResourceName().substring(prefix.length()), ClassPath.ResourceInfo::url) ); files.forEach((name, url) -> { Path file = output.resolve(name); try (InputStream is = url.openStream()) { Files.copy(is, file); } catch (IOException e) { throw new RuntimeException(String.format("name: %s, url: %s", name, url), e); } }); }
public static Iterator<ClassInfo> classes(String... packages) throws IOException { ClassPath path = ClassPath.from(ReflectionUtil.class.getClassLoader()); ExtendableIterator<ClassInfo> results = new ExtendableIterator<>(); for (String p : packages) { results.extend(path.getTopLevelClassesRecursive(p).iterator()); } return results; }
ClassPath classPath = ClassPath.from(classLoader); ImmutableSet<ClassInfo> classes = packageName == null ? classPath.getAllClasses() : classPath.getTopLevelClassesRecursive(packageName); for (ClassInfo classInfo : classes) Class<?> clazz = classInfo.load(); PluginDescriptor pluginDescriptor = clazz.getAnnotation(PluginDescriptor.class);
.from(Thread.currentThread().getContextClassLoader()); packages.forEach(packageName -> classPath.getTopLevelClassesRecursive(packageName) .forEach(classInfo -> final Class<?> checkClass = classInfo.load(); if (checkType.isAssignableFrom(checkClass) && !Modifier.isAbstract(checkClass.getModifiers())
public void testNulls() throws IOException { new NullPointerTester().testAllPublicStaticMethods(ClassPath.class); new NullPointerTester() .testAllPublicInstanceMethods(ClassPath.from(getClass().getClassLoader())); }
public Collection<ClassResource> getAllClasses() throws IOException { Collection<ClassResource> result = new ArrayList<>(getRuntimeClasses()); for (ClassPath.ClassInfo classInfo : ClassPath.from(classLoader).getAllClasses()) { result.add(new ClassLoaderClassResource(classLoader, classInfo.getResourceName())); } return result; }
} catch (SecurityException expected) { ClassPath classPath = ClassPath.from(getClass().getClassLoader()); for (ResourceInfo resource : classPath.getResources()) { assertThat(resource.getResourceName()).doesNotContain("com/google/common/reflect/");
public static void main(String[] args) throws IOException { ClassPath p = ClassPath.from(ClassLoader.getSystemClassLoader()); // might need to provide different ClassLoader ImmutableSet<ClassInfo> classes = p.getTopLevelClasses("com.example"); for (ClassInfo classInfo : classes) { Class clazz = classInfo.load(); int modifiers = clazz.getModifiers(); if (Modifier.isAbstract(modifiers)) { System.out.println("Class '" + clazz.getName() + "' is abstract."); } } }
/** * Returns a {@code ClassPath} representing all classes and resources loadable from {@code * classloader} and its parent class loaders. * * <p>Currently only {@link URLClassLoader} and only {@code file://} urls are supported. * * @throws IOException if the attempt to read class path resources (jar files or directories) * failed. */ public static ClassPath from(ClassLoader classloader) throws IOException { Scanner scanner = new Scanner(); for (Map.Entry<URI, ClassLoader> entry : getClassPathEntries(classloader).entrySet()) { scanner.scan(entry.getKey(), entry.getValue()); } return new ClassPath(scanner.getResources()); }
public class OwnerFinder { public static void main(String[] args) { try { ClassPath classPath = ClassPath.from(OwnerFinder.class.getClassLoader()); classPath.getTopLevelClassesRecursive("com.somepackage") .stream() .filter(c -> c.getSimpleName().equals("package-info")) .map(c -> c.load().getPackage().getAnnotation(PackageOwner.class)) .forEach(a -> System.out.println(a.owner())); } catch(IOException e) { e.printStackTrace(); } } }