Example usage for com.google.common.reflect ClassPath from

List of usage examples for com.google.common.reflect ClassPath from

Introduction

In this page you can find the example usage for com.google.common.reflect ClassPath from.

Prototype

public static ClassPath from(ClassLoader classloader) throws IOException 

Source Link

Document

Returns a ClassPath representing all classes and resources loadable from classloader and its parent class loaders.

Usage

From source file:games.stendhal.server.script.ListRaids.java

/**
 * Fetch classes of available scripts./* w w w.j  a va 2 s.  com*/
 * 
 * @param pckgname the package name of scripts
 * @return list of script classes
 * @throws ClassNotFoundException if getting the class loader or reading the
 *    script resources fail
 */
private static ArrayList<Class<?>> getClasses(final String pckgname) throws ClassNotFoundException {
    final ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
    try {
        ClassLoader classLoader = ListRaids.class.getClassLoader();
        String packageName = "games.stendhal.server.script";
        ImmutableSet<ClassInfo> infos = ClassPath.from(classLoader).getTopLevelClasses(packageName);
        for (ClassInfo info : infos) {
            classes.add(info.load());
        }
        return classes;
    } catch (IOException e) {
        throw new ClassNotFoundException("failed to list classes");
    }
}

From source file:nl.knaw.huygens.timbuctoo.tools.util.metadata.MetaDataGeneratorTool.java

public void execute() throws IllegalArgumentException, IllegalAccessException {
    ClassPath classPath = null;//from   w ww  . j  a v  a  2s .c o  m
    try {
        classPath = ClassPath.from(this.getClass().getClassLoader());
    } catch (IOException e) {
        LOG.error("Could not load classpath", e);
        return;
    }

    for (ClassInfo info : classPath.getTopLevelClassesRecursive("nl.knaw.huygens.timbuctoo.model")) {
        String name = info.getName();
        try {
            Class<?> type = Class.forName(name);

            createMetaData(type, null);

            // create metadata for the inner classes aswell.
            for (Class<?> declaredType : type.getDeclaredClasses()) {
                createMetaData(declaredType, type);
            }

        } catch (ClassNotFoundException e) {
            LOG.info("Could not find class {}", name);
        }
    }
}

From source file:org.gbif.registry.ws.resources.EnumerationResource.java

private static Map<String, Enum<?>[]> enumerations() {
    try {//from w  ww . j  a v a  2 s . com
        ClassPath cp = ClassPath.from(EnumerationResource.class.getClassLoader());
        ImmutableMap.Builder<String, Enum<?>[]> builder = ImmutableMap.builder();

        List<ClassInfo> infos = cp.getTopLevelClasses(Country.class.getPackage().getName()).asList();
        for (ClassInfo info : infos) {
            Class<? extends Enum<?>> vocab = VocabularyUtils.lookupVocabulary(info.getName());
            // verify that it is an Enumeration
            if (vocab != null && vocab.getEnumConstants() != null) {
                builder.put(info.getSimpleName(), vocab.getEnumConstants());
            }
        }
        return builder.build();

    } catch (Exception e) {
        LOG.error("Unable to read the classpath for enumerations", e);
        return ImmutableMap.<String, Enum<?>[]>of(); // empty
    }
}

From source file:com.prepaird.objectgraphdb.OrientDbConnector.java

private static void loadClasses(Collection<String> coll, String packageName) throws IOException {
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    for (final ClassPath.ClassInfo classInfo : ClassPath.from(loader)
            .getTopLevelClassesRecursive(packageName)) {
        if (classInfo.load().getSuperclass().equals(Object.class)) {
            coll.add(classInfo.getSimpleName());
        }//from www. j a  v  a  2  s  .co m
    }
}

From source file:luca.plugins.cmd.LCommands.java

private void registerCommands() throws Exception {
    Field field = Bukkit.getPluginManager().getClass().getDeclaredField("commandMap");
    field.setAccessible(true);//from  w  w  w . j av  a 2 s. co m
    CommandMap map = (CommandMap) field.get(Bukkit.getPluginManager());
    getLogger().info("Starting dynamic command registration...");
    int i = 0;
    for (ClassPath.ClassInfo info : ClassPath.from(getClassLoader())
            .getTopLevelClasses("luca.plugins.cmd.commands")) {
        CustomCommand cmd = (CustomCommand) info.load().getConstructor().newInstance();
        map.register(getName().toLowerCase(), new BukkitExecutor(cmd));
        i++;
    }
    getLogger().info(i + " commands have been registered.");
}

From source file:com.qmetry.qaf.automation.util.GuavaClassFinderImpl.java

@Override
public List<Class<?>> getClasses(String pkg) throws IOException {
    List<Class<?>> classes = new ArrayList<Class<?>>();
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    for (final ClassPath.ClassInfo info : ClassPath.from(loader).getTopLevelClasses()) {
        if (info.getName().startsWith(pkg)) {
            final Class<?> clazz = info.load();
            classes.add(clazz);//from w  w w .  jav a 2  s  .c o  m
        }
    }
    return classes;
}

From source file:com.avatarproject.core.configuration.Config.java

public static void loadConfigurations(JavaPlugin plugin, String packageName) {
    ClassLoader loader = plugin.getClass().getClassLoader();
    try {/*from www . ja  va 2 s  .  c  om*/
        ClassPath.from(loader).getAllClasses().stream().filter(info -> {
            if (!info.getPackageName().startsWith(packageName)) {
                return false;
            }
            Class<?> c = info.load();
            if (!Config.class.isAssignableFrom(c) || c.isInterface() || Modifier.isAbstract(c.getModifiers())) {
                return false;
            }
            return true;
        }).forEach(info -> {
            Class<?> c = info.load();
            try {
                c.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
        });

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:pl.wavesoftware.wfirma.api.core.mapper.xml.JaxbMarshaller.java

protected JAXBContext getContext() {
    try {/* w w w. java 2  s.  c  om*/
        final Package pack = type.getPackage();
        final ClassLoader loader = Thread.currentThread().getContextClassLoader();

        Set<Class<?>> classes = new HashSet<>();
        for (final ClassPath.ClassInfo info : ClassPath.from(loader).getTopLevelClasses()) {
            if (info.getName().startsWith(pack.getName()) && !info.getName().endsWith("Test")) {
                classes.add(info.load());
            }
        }
        Class<?>[] arr = new Class<?>[classes.size()];
        classes.toArray(arr);
        return JAXBContext.newInstance(arr);
    } catch (JAXBException | IOException ex) {
        throw new EidIllegalStateException("20150716:113108", ex);
    }
}

From source file:objenome.util.Packatainer.java

public static Set<ClassPath.ClassInfo> getPackageClasses(String packege) throws Exception {
    //https://code.google.com/p/guava-libraries/wiki/ReflectionExplained#ClassPath
    ClassPath classpath = ClassPath.from(Packatainer.class.getClassLoader());

    return classpath.getTopLevelClasses(packege);
}

From source file:org.diqube.data.serialize.DataSerializationManager.java

@PostConstruct
public void initialize() {
    ImmutableSet<ClassInfo> classInfos;
    try {// w  ww  . j  a v  a2s.  co  m
        classInfos = ClassPath.from(this.getClass().getClassLoader()).getTopLevelClassesRecursive(BASE_PKG);
    } catch (IOException e) {
        throw new RuntimeException("Could not parse ClassPath.");
    }

    for (ClassInfo classInfo : classInfos) {
        Class<?> clazz = classInfo.load();

        if (!DataSerialization.class.isAssignableFrom(clazz))
            continue;

        Deque<Class<?>> allClasses = new LinkedList<>();
        allClasses.add(clazz);
        while (!allClasses.isEmpty()) {
            Class<?> curClazz = allClasses.pop();
            if (curClazz.getDeclaredAnnotation(DataSerializableIgnore.class) != null)
                break;

            DataSerializable ann = curClazz.getDeclaredAnnotation(DataSerializable.class);
            if (ann != null) {
                @SuppressWarnings("unchecked")
                Class<? extends DataSerialization<?>> datSerClazz = (Class<? extends DataSerialization<?>>) clazz;

                Class<? extends TBase<?, ?>> thriftClass = ann.thriftClass();
                Class<? extends DataSerializationDelegationManager<?>> delegationManagerClass = ann
                        .deserializationDelegationManager();

                thriftClasses.put(datSerClazz, thriftClass);
                liveClasses.put(thriftClass, datSerClazz);

                if (!delegationManagerClass.equals(DataSerializable.NONE.class)) {
                    try {
                        DataSerializationDelegationManager<?> delegationManager = delegationManagerClass
                                .newInstance();

                        delegationManagers.put(thriftClass, delegationManager);
                    } catch (InstantiationException | IllegalAccessException e) {
                        throw new RuntimeException("Could not instantiate " + delegationManagerClass);
                    }
                }
                break;
            }
            if (curClazz.getSuperclass() != null && !curClazz.getSuperclass().equals(Object.class))
                allClasses.add(curClazz.getSuperclass());
            allClasses.addAll(Arrays.asList(curClazz.getInterfaces()));
        }
    }
}