4

I am working on a maven project and I added to my pom.xml file the guava dependency and the dependency of an other project. I want to get all class of a given package of that project which I have added to my pom as a dependency. So I tried with this :

public void getClassOfPackage() {

    final ClassLoader loader = Thread.currentThread()
            .getContextClassLoader();
    try {
        for (final ClassPath.ClassInfo info : ClassPath.from(loader)
                .getTopLevelClasses()) {

                System.out.println(info.getSimpleName());

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

}

public static void main(String[] args) {
    new TestMain().getClassOfPackage();
}

And I know that is wrong because it gives that in console:

HierarchicalConfigurationConverter
HierarchicalConfigurationXMLReader
HierarchicalINIConfiguration
SubsetConfiguration
SystemConfiguration...

I don't know where I can specify the project where I am talking about and how I can just pass the package name and it gives me all class which it contains.

ThisClark
  • 14,352
  • 10
  • 69
  • 100
Abder KRIMA
  • 3,418
  • 5
  • 31
  • 54
  • What's your question, exactly? Are you asking how you can get the classes from the lines? Have you tried parsing them? It seems like you could split them along the `$` and whatever's on the right is your classname. – Nic Feb 04 '15 at 17:18
  • i have a package named org.mypackage where i have a lot of Entities so i want in the class above to pass juste the package name "org.mypackage" and the programme show me all class name of that package – Abder KRIMA Feb 04 '15 at 17:26
  • Oh, I misunderstood what you were asking. Could you put a sentence in at the end explaining that? – Nic Feb 04 '15 at 17:26
  • 1
    yes of course and it's done now – Abder KRIMA Feb 04 '15 at 17:28

4 Answers4

2

I can show all the classes whitch are in the same project but for an other project added as a dependency in pom.xml not yet :

The solution for what we i have in the same project:

 public void getClassOfPackage() {

    final ClassLoader loader = Thread.currentThread()
            .getContextClassLoader();
    try {

        ClassPath classpath = ClassPath.from(loader); // scans the class path used by classloader
        for (ClassPath.ClassInfo classInfo : classpath.getTopLevelClasses("org.mypackage")) {
          System.out.println(classInfo.getSimpleName()+" <==> "+classInfo.getPackageName());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

}

public static void main(String[] args) {
    new TestMain().getClassOfPackage();
}
Abder KRIMA
  • 3,418
  • 5
  • 31
  • 54
2

I found tow solutions :

With guava :

public void getClassOfPackage(String packagenom) {

    final ClassLoader loader = Thread.currentThread()
            .getContextClassLoader();
    try {

        ClassPath classpath = ClassPath.from(loader); // scans the class path used by classloader
        for (ClassPath.ClassInfo classInfo : classpath.getTopLevelClasses(packagenom)) {
         if(!classInfo.getSimpleName().endsWith("_")){
            System.out.println(classInfo.getSimpleName());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

}

public static void main(String[] args) {
    new TestMain().getClassOfPackage("org.myproject");
}

With Java.util:

    public List<Class> getClassOfPackage(String packageName)
        throws ClassNotFoundException, IOException {

    ClassLoader classLoader = Thread.currentThread()
            .getContextClassLoader();

    assert classLoader != null;
    String path = packageName.replace('.', '/');
    Enumeration<URL> resources = classLoader.getResources(path);
    List<File> dirs = new ArrayList<File>();
    while (resources.hasMoreElements()) {
        URL resource = resources.nextElement();
        dirs.add(new File(resource.getFile()));
    }
    ArrayList<Class> classes = new ArrayList<Class>();
    for (File directory : dirs) {
        classes.addAll(findClasses(directory, packageName));
    }
    return classes;
}

private static List<Class> findClasses(File directory, String packageName)
        throws ClassNotFoundException {
    List<Class> classes = new ArrayList<Class>();
    if (!directory.exists()) {
        return classes;
    }
    File[] files = directory.listFiles();
    for (File file : files) {
        if (file.isDirectory()) {
            assert !file.getName().contains(".");
            classes.addAll(findClasses(file,
                    packageName + "." + file.getName()));
        } else if (file.getName().endsWith(".class")) {
            classes.add(Class.forName(packageName
                    + '.'
                    + file.getName().substring(0,
                            file.getName().length() - 6)));
        }
    }
    return classes;
}

public static void main(String[] args) throws ClassNotFoundException,
        IOException {

    for (Class className : new ClassOfPackage()
            .getClassOfPackage("org.mypackage")) {
        if (!className.getSimpleName().endsWith("_")) {
            System.out.println(className.getSimpleName());
        }

    }

}
Abder KRIMA
  • 3,418
  • 5
  • 31
  • 54
1

This is why you're seeing it print out sun.misc.Launcher$AppClassLoader:

} else {
     System.out.println(loader.getClass().getName());
}

Every class on your classpath that isn't in your package is causing your program to print out the name of the ClassLoader implementation class, which you probably don't want.

Also, while info.getName().startsWith("org.mypackage") should work, it might be preferable to write info.getPackageName().equals("org.mypackage") (or startsWith if you want to include subpackages too).

ColinD
  • 108,630
  • 30
  • 201
  • 202
  • @TinyOS: Your edit doesn't change anything about my answer, though I did edit it to try to make it more clear. I've explained why you're seeing the output you're seeing. Does making that change fix things for you? – ColinD Feb 04 '15 at 17:53
-1

It is easier to solve this problem with the help of Google reflections.

Please check the following question for the correct answer - note that the checked answer does not provide a working solution, the second one (Aleksander Blomskøld) does!

Community
  • 1
  • 1
Fritz Duchardt
  • 11,026
  • 4
  • 41
  • 60
  • i try juste with guava and it works , you can see my answer bellow but the problem now is : how to show all classes of a given package in other project whitch added to the current application by maven dependencies : More details: I have my main maven project where i want to show all classes of an other project nammed services. and i have the dependency of services project in the pom of my main project . I hope that my issue is clear for you now – Abder KRIMA Feb 05 '15 at 10:17