package com.MyUtils.file;  

[java] view plain copy

    import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile; /**
* 扫描包下路径
* 包括本地文件和jar包文件
* @author ljb
*
*/
public class ScanningFile { private Class<?> superStrategy = String.class;//接口类class 用于过滤 可以不要 private List<Class<? extends String>> eleStrategyList = new ArrayList<Class<? extends String>>(); private ClassLoader classLoader = ScanningFile.class.getClassLoader();//默认使用的类加载器 private static final String STARATEGY_PATH = "com.MyUtils.file";//需要扫描的策略包名 public static void main(String[] args) {
ScanningFile s = new ScanningFile();
s.addClass();
} /**
* 获取包下所有实现了superStrategy的类并加入list
*/
private void addClass(){
URL url = classLoader.getResource(STARATEGY_PATH.replace(".", "/"));
String protocol = url.getProtocol();
if ("file".equals(protocol)) {
// 本地自己可见的代码
findClassLocal(STARATEGY_PATH);
} else if ("jar".equals(protocol)) {
// 引用jar包的代码
findClassJar(STARATEGY_PATH);
}
} /**
* 本地查找
* @param packName
*/
private void findClassLocal(final String packName){
URI url = null ;
try {
url = classLoader.getResource(packName.replace(".", "/")).toURI();
} catch (URISyntaxException e1) {
throw new RuntimeException("未找到策略资源");
} File file = new File(url);
file.listFiles(new FileFilter() { public boolean accept(File chiFile) {
if(chiFile.isDirectory()){
findClassLocal(packName+"."+chiFile.getName());
}
if(chiFile.getName().endsWith(".class")){
Class<?> clazz = null;
try {
clazz = classLoader.loadClass(packName + "." + chiFile.getName().replace(".class", ""));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println(chiFile);
if(superStrategy.isAssignableFrom(clazz)){
eleStrategyList.add((Class<? extends String>) clazz);
}
return true;
}
return false;
}
}); } /**
* jar包查找
* @param packName
*/
private void findClassJar(final String packName){
String pathName = packName.replace(".", "/");
JarFile jarFile = null;
try {
URL url = classLoader.getResource(pathName);
JarURLConnection jarURLConnection = (JarURLConnection )url.openConnection();
jarFile = jarURLConnection.getJarFile();
} catch (IOException e) {
throw new RuntimeException("未找到策略资源");
} Enumeration<JarEntry> jarEntries = jarFile.entries();
while (jarEntries.hasMoreElements()) {
JarEntry jarEntry = jarEntries.nextElement();
String jarEntryName = jarEntry.getName(); if(jarEntryName.contains(pathName) && !jarEntryName.equals(pathName+"/")){
//递归遍历子目录
if(jarEntry.isDirectory()){
String clazzName = jarEntry.getName().replace("/", ".");
int endIndex = clazzName.lastIndexOf(".");
String prefix = null;
if (endIndex > 0) {
prefix = clazzName.substring(0, endIndex);
}
findClassJar(prefix);
}
if(jarEntry.getName().endsWith(".class")){
Class<?> clazz = null;
try {
clazz = classLoader.loadClass(jarEntry.getName().replace("/", ".").replace(".class", ""));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if(superStrategy.isAssignableFrom(clazz)){
eleStrategyList.add((Class<? extends String>) clazz);
}
}
} } } }
  1. package com.MyUtils.file;
  1. import java.io.File;
  2. import java.io.FileFilter;
  3. import java.io.IOException;
  4. import java.net.JarURLConnection;
  5. import java.net.URI;
  6. import java.net.URISyntaxException;
  7. import java.net.URL;
  8. import java.util.ArrayList;
  9. import java.util.Enumeration;
  10. import java.util.List;
  11. import java.util.jar.JarEntry;
  12. import java.util.jar.JarFile;
  13. /**
  14. * 扫描包下路径
  15. * 包括本地文件和jar包文件
  16. * @author ljb
  17. *
  18. */
  19. public class ScanningFile {
  20. private Class<?> superStrategy = String.class;//接口类class 用于过滤 可以不要
  21. private List<Class<? extends String>> eleStrategyList = new ArrayList<Class<? extends String>>();
  22. private ClassLoader classLoader = ScanningFile.class.getClassLoader();//默认使用的类加载器
  23. private static final String STARATEGY_PATH = "com.MyUtils.file";//需要扫描的策略包名
  24. public static void main(String[] args) {
  25. ScanningFile s = new ScanningFile();
  26. s.addClass();
  27. }
  28. /**
  29. * 获取包下所有实现了superStrategy的类并加入list
  30. */
  31. private void addClass(){
  32. URL url = classLoader.getResource(STARATEGY_PATH.replace(".", "/"));
  33. String protocol = url.getProtocol();
  34. if ("file".equals(protocol)) {
  35. // 本地自己可见的代码
  36. findClassLocal(STARATEGY_PATH);
  37. } else if ("jar".equals(protocol)) {
  38. // 引用jar包的代码
  39. findClassJar(STARATEGY_PATH);
  40. }
  41. }
  42. /**
  43. * 本地查找
  44. * @param packName
  45. */
  46. private void findClassLocal(final String packName){
  47. URI url = null ;
  48. try {
  49. url = classLoader.getResource(packName.replace(".", "/")).toURI();
  50. } catch (URISyntaxException e1) {
  51. throw new RuntimeException("未找到策略资源");
  52. }
  53. File file = new File(url);
  54. file.listFiles(new FileFilter() {
  55. public boolean accept(File chiFile) {
  56. if(chiFile.isDirectory()){
  57. findClassLocal(packName+"."+chiFile.getName());
  58. }
  59. if(chiFile.getName().endsWith(".class")){
  60. Class<?> clazz = null;
  61. try {
  62. clazz = classLoader.loadClass(packName + "." + chiFile.getName().replace(".class", ""));
  63. } catch (ClassNotFoundException e) {
  64. e.printStackTrace();
  65. }
  66. System.out.println(chiFile);
  67. if(superStrategy.isAssignableFrom(clazz)){
  68. eleStrategyList.add((Class<? extends String>) clazz);
  69. }
  70. return true;
  71. }
  72. return false;
  73. }
  74. });
  75. }
  76. /**
  77. * jar包查找
  78. * @param packName
  79. */
  80. private void findClassJar(final String packName){
  81. String pathName = packName.replace(".", "/");
  82. JarFile jarFile  = null;
  83. try {
  84. URL url = classLoader.getResource(pathName);
  85. JarURLConnection jarURLConnection  = (JarURLConnection )url.openConnection();
  86. jarFile = jarURLConnection.getJarFile();
  87. } catch (IOException e) {
  88. throw new RuntimeException("未找到策略资源");
  89. }
  90. Enumeration<JarEntry> jarEntries = jarFile.entries();
  91. while (jarEntries.hasMoreElements()) {
  92. JarEntry jarEntry = jarEntries.nextElement();
  93. String jarEntryName = jarEntry.getName();
  94. if(jarEntryName.contains(pathName) && !jarEntryName.equals(pathName+"/")){
  95. //递归遍历子目录
  96. if(jarEntry.isDirectory()){
  97. String clazzName = jarEntry.getName().replace("/", ".");
  98. int endIndex = clazzName.lastIndexOf(".");
  99. String prefix = null;
  100. if (endIndex > 0) {
  101. prefix = clazzName.substring(0, endIndex);
  102. }
  103. findClassJar(prefix);
  104. }
  105. if(jarEntry.getName().endsWith(".class")){
  106. Class<?> clazz = null;
  107. try {
  108. clazz = classLoader.loadClass(jarEntry.getName().replace("/", ".").replace(".class", ""));
  109. } catch (ClassNotFoundException e) {
  110. e.printStackTrace();
  111. }
  112. if(superStrategy.isAssignableFrom(clazz)){
  113. eleStrategyList.add((Class<? extends String>) clazz);
  114. }
  115. }
  116. }
  117. }
  118. }
  119. }

Java 扫描包下所有类(包括jar包)的更多相关文章

  1. java在cmd下编译引用第三方jar包

    java在cmd下编译引用第三方jar包 转 https://blog.csdn.net/qq_21439971/article/details/53924594 获取第三方jar包 第三包我们可以引 ...

  2. java动态载入指定的类或者jar包反射调用其方法

    序言 有时候.项目中会用到java动态载入指定的类或者jar包反射调用其方法来达到模块的分离,使各个功能之间耦合性大大减少,更加的模块化.代码利用率更高.模式中的代理模式就用到java的这一机制. 下 ...

  3. java 查找指定包下的类

    package com.jason.test; import java.io.File; import java.io.IOException; import java.io.UnsupportedE ...

  4. Eclipse中将java类打成jar包形式运行

    记录一次帮助小伙伴将java类打成jar包运行 1.创建java project项目 file > new > project > java project 随便起一个项目名称,fi ...

  5. java.io 包下的类有哪些 + 面试题

    java.io 包下的类有哪些 + 面试题 IO 介绍 IO 是 Input/Output 的缩写,它是基于流模型实现的,比如操作文件时使用输入流和输出流来写入和读取文件等. IO 分类 传统的 IO ...

  6. java项目中可能会使用到的jar包解释

    一.Struts2 用的版本是struts2.3.1.1 一个简单的Struts项目所需的jar包有如下8个 1. struts2-core-2.3.1.1.jar: Struts2的核心类库. 2. ...

  7. 【BUG】websphere找不到类或jar包冲突

    来自:http://liuwei1578.blog.163.com/blog/static/49580364200991572642653/ Jar包冲突问题是在大型Java软件开发中经常遇到的问题, ...

  8. JAVA、android中常用的一些jar包的作用

    正文: 这里主要介绍的是hibernate使用到的.jar Hibernate一共包括了23个jar包,令人眼花缭乱.本文将详细讲解Hibernate每个jar包的作用,便于你在应用中根据自己的需要进 ...

  9. java命令行从编译到打jar包到执行

     目录: 一. javac编译     1. 没有额外的jar包     2. 包含额外的jar包 二. jar打jar包 三. java运行     1. java命令执行     2. jar包执 ...

  10. Linux查找class类所在jar包

    1.说明 写代码或者定位问题的时候, 经常发生只知道类名不知道其所在jar包的问题, 在Eclipse中可以使用Ctrl+Shift+T查找类, 但是如果类所在的jar包不在Build Path中, ...

随机推荐

  1. 【容斥原理】CDOJ - 1544 - 当咸鱼也要按照基本法

    众所周知zhu是一个大厨,zhu一直有自己独特的咸鱼制作技巧. tang是一个咸鱼供应商,他告诉zhu在他那里面有NN条咸鱼(标号从1到N)可以被用来制作. 每条咸鱼都有一个咸鱼值KiKi,初始时所有 ...

  2. iOS开发-设置在使用NavigateController时View的顶部位置

      最近我在开发中遇到了一个问题,在使用NavigationController时内部的ViewController的View总是与屏幕顶部对齐,而我们有时候不需要这种效果: 在开发过程中,我们可能会 ...

  3. win10 彻底删除mysql步骤

    转载自:https://blog.csdn.net/sxingming/article/details/52601250 1. 停止MySQL服务 开始->所有应用->Windows管理工 ...

  4. iOS:Masonry练习详解

    Masonry练习详解   添加约束的方式: 1.通过使用NSLayoutConstraints添加约束到约束数组中,之前必须设置translatesAutoresizingMaskIntoConst ...

  5. numpy基础知识

    官网简介: http://www.numpy.org/ ndarry基本属性 ndarry是Numpy中的N维数组对象(N dimentional arrya,ndarray) ndarry中所有的元 ...

  6. 利用JS实现vue中的双向绑定

    Vue 已经是主流框架了 它的好处也不用多说,都已经是大家公认的了 那我们就来理解一下Vue的单向数据绑定和双向数据绑定 然后再使用JS来实现Vue的双向数据绑定 单向数据绑定 指的是我们先把模板写好 ...

  7. infer 编译代码审查命令记录

    infer -- xcodebuild -target <target name> -configuration <build configuration> -sdk ipho ...

  8. JMS两种消息模型

    前段时间学习EJB.接触到了JMS(Java消息服务),JMS支持两种消息模型:Point-to-Point(P2P)和Publish/Subscribe(Pub/Sub),即点对点和公布订阅模型. ...

  9. C语言字符串操作总结大全(超具体)

    1)字符串操作 strcpy(p, p1) 复制字符串 strncpy(p, p1, n) 复制指定长度字符串 strcat(p, p1) 附加字符串 strncat(p, p1, n) 附加指定长度 ...

  10. css处理超出文本截断问题的两种情况(多行或者单行)

    1.非多行的简单处理方式: css代码: .words{ width:400px; overflow:hidden; /*超过部分不显示*/ text-overflow:ellipsis; /*超过部 ...