java实现遍历某个包下的Class,注意不是自己写的包。是Java自身的吧。如:java.io

java实现遍历某个包下的Class,注意不是自己写的包。是Java自身的吧。如:java.io

问题描述:

java实现遍历某个包下的Class,注意不是自己写的包。是Java自身的吧。如:java.io包下的所有Class和interface

简单说一下方法(假设你要找java.io包下的class)
String javaHome = System.getProperty("java.home");
JarFile jf = new JarFile(javaHome + "/jre/lib/rt.jar");
jf.stream().filter(je -> Pattern.compile("java/io/[A-Z]+[a-z].class").matcher(je.getName()).matches()).foreach(je -> {
... // Add your code here.
});
我这里用了Java 8的lambda语法;如果你不熟悉,基本方法就是便利rt.jar,找出所有的java/io/xxx.class

参考:http://blog.csdn.net/wangpeng047/article/details/8124390
代码如下:

01.package com.itkt.mtravel.hotel.util;

02.

03.import java.io.File;

04.import java.util.ArrayList;

05.import java.util.List;

06.

07.public class PackageUtil {

08.

09. public static void main(String[] args) {

10. String packageName = "com.itkt.mtravel.hotel";

11.

12. List classNames = getClassName(packageName);

13. for (String className : classNames) {

14. System.out.println(className);

15. }

16. }

17.

18. public static List getClassName(String packageName) {

19. String filePath = ClassLoader.getSystemResource("").getPath() + packageName.replace(".", "\");

20. List fileNames = getClassName(filePath, null);

21. return fileNames;

22. }

23.

24. private static List getClassName(String filePath, List className) {

25. List myClassName = new ArrayList();

26. File file = new File(filePath);

27. File[] childFiles = file.listFiles();

28. for (File childFile : childFiles) {

29. if (childFile.isDirectory()) {

30. myClassName.addAll(getClassName(childFile.getPath(), myClassName));

31. } else {

32. String childFilePath = childFile.getPath();

33. childFilePath = childFilePath.substring(childFilePath.indexOf("\classes") + 9, childFilePath.lastIndexOf("."));

34. childFilePath = childFilePath.replace("\", ".");

35. myClassName.add(childFilePath);

36. }

37. }

38.

39. return myClassName;

40. }

41.}