2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

How can I find the class names contains in a package by using java reflection?

I am looking for to find out the classes or interfaces available under the given package name.

e.g If I will give the input as "com.test.common" then it will give me the above result.

Thanks in advance!

userimage

Here Is an Example which you are looking for.

I have a Corejava App and its contain some classes under an package com.test.code and by using the below code we can able to get the class names.


  1. package com.test.reflection;

  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.net.URL;
  5. import java.util.ArrayList;
  6. import java.util.Enumeration;
  7. import java.util.List;
  8. public class GetAllClasses {
  9. private static Class[] getClasses(String packageName)
  10. throws ClassNotFoundException, IOException {
  11. ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
  12. assert classLoader != null;
  13. String path = packageName.replace('.', '/');
  14. Enumeration<URL> resources = classLoader.getResources(path);
  15. List<File> dirs = new ArrayList<File>();
  16. while (resources.hasMoreElements()) {
  17. URL resource = resources.nextElement();
  18. dirs.add(new File(resource.getFile()));
  19. }
  20. ArrayList<Class> classes = new ArrayList<Class>();
  21. for (File directory : dirs) {
  22. classes.addAll(findClasses(directory, packageName));
  23. }
  24. return classes.toArray(new Class[classes.size()]);
  25. }
  26. private static List<Class> findClasses(File directory, String packageName) throws ClassNotFoundException {
  27. List<Class> classes = new ArrayList<Class>();
  28. if (!directory.exists()) {
  29. return classes;
  30. }
  31. File[] files = directory.listFiles();
  32. for (File file : files) {
  33. if (file.isDirectory()) {
  34. assert !file.getName().contains(".");
  35. classes.addAll(findClasses(file, packageName + "." + file.getName()));
  36. } else if (file.getName().endsWith(".class")) {
  37. classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
  38. }
  39. }
  40. return classes;
  41. }
  42. public static void main(String[] args) throws ClassNotFoundException, IOException {
  43. Class[] classes = getClasses("com.test.code");
  44. for(Class myClasses : classes){
  45. System.out.println(myClasses);
  46. }
  47. }
  48. }




Output:

class com.test.code.ConcatQuote
class com.test.code.TagsSeparation
class com.test.code.TestIf
class com.test.code.TestPattern
class com.test.code.TestPatternCompile
class com.test.code.TestRuntime
class com.test.code.TestSize
class com.test.code.TestSplit
class com.test.code.TestTime

Answer is