Java 扫描包下所有类(包括jar包)
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);
}
}
}
}
}
}
- package com.MyUtils.file;
- 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);
- }
- }
- }
- }
- }
- }
Java 扫描包下所有类(包括jar包)的更多相关文章
- java在cmd下编译引用第三方jar包
java在cmd下编译引用第三方jar包 转 https://blog.csdn.net/qq_21439971/article/details/53924594 获取第三方jar包 第三包我们可以引 ...
- java动态载入指定的类或者jar包反射调用其方法
序言 有时候.项目中会用到java动态载入指定的类或者jar包反射调用其方法来达到模块的分离,使各个功能之间耦合性大大减少,更加的模块化.代码利用率更高.模式中的代理模式就用到java的这一机制. 下 ...
- java 查找指定包下的类
package com.jason.test; import java.io.File; import java.io.IOException; import java.io.UnsupportedE ...
- Eclipse中将java类打成jar包形式运行
记录一次帮助小伙伴将java类打成jar包运行 1.创建java project项目 file > new > project > java project 随便起一个项目名称,fi ...
- java.io 包下的类有哪些 + 面试题
java.io 包下的类有哪些 + 面试题 IO 介绍 IO 是 Input/Output 的缩写,它是基于流模型实现的,比如操作文件时使用输入流和输出流来写入和读取文件等. IO 分类 传统的 IO ...
- java项目中可能会使用到的jar包解释
一.Struts2 用的版本是struts2.3.1.1 一个简单的Struts项目所需的jar包有如下8个 1. struts2-core-2.3.1.1.jar: Struts2的核心类库. 2. ...
- 【BUG】websphere找不到类或jar包冲突
来自:http://liuwei1578.blog.163.com/blog/static/49580364200991572642653/ Jar包冲突问题是在大型Java软件开发中经常遇到的问题, ...
- JAVA、android中常用的一些jar包的作用
正文: 这里主要介绍的是hibernate使用到的.jar Hibernate一共包括了23个jar包,令人眼花缭乱.本文将详细讲解Hibernate每个jar包的作用,便于你在应用中根据自己的需要进 ...
- java命令行从编译到打jar包到执行
目录: 一. javac编译 1. 没有额外的jar包 2. 包含额外的jar包 二. jar打jar包 三. java运行 1. java命令执行 2. jar包执 ...
- Linux查找class类所在jar包
1.说明 写代码或者定位问题的时候, 经常发生只知道类名不知道其所在jar包的问题, 在Eclipse中可以使用Ctrl+Shift+T查找类, 但是如果类所在的jar包不在Build Path中, ...
随机推荐
- python基础之二
1. 数据类型 1.1 数字 数字的作用:与数字相关,例如:手机号.QQ号.身份证号等,用数字表示 数字分为:整数(int).浮点数(float).复数(了解) 例子: age = 10 print( ...
- Java高级架构师(一)第08节:基本业务功能和数据字典
- oop 知识点回顾
1.抽象,封装 2.继承:连接类的层次模型,并且允许类的重用,提供共性的方法,从现有的类派生(方法的重写,扩展) 派生:新类继承了基类,那么新类就是派生类,适合更合适的需要 3.多态:允许不同的类的对 ...
- iOS开发之指定UIView的某几个角为圆角
我们知道, 如果需要将UIView的4个角全部都为圆角,做法相当简单,只需设置其Layer的cornerRadius属性即可(项目需要使用QuartzCore框架).而若要指定某几个角(小于4)为圆角 ...
- Java静态static工具类线程安全问题研究
针对静态方法有以下一些前提: 静态方法和实例方法的区别是静态方法只能引用静态变量,静态方法通过类名来调用,实例方法通过对象实例来调用 每个线程都有自己的线程栈,栈与线程同时创建,每一个虚拟机线程都有自 ...
- ORA-12537:TNS:连接关闭 -------数据库最大连接数问题
问题: 我自己用PLSQL登录实验,我也登陆不了,可是让同事实验,他一会能够登录,一会不能够登录.应用还是能够正常访问,只是PLSQL登录异常. 分析: 基于这种情况去百度,有的说是配置文件有问题,有 ...
- Docker时间和宿主同步
通过date命令查看时间 查看主机时间 [root@localhost ~]# date 2016年 07月 27日 星期三 22:42:44 CST 查看容器时间 root@b43340ecf5ef ...
- 关于接口 RandomAccess
今天看到java.util.Collections这个工具类中的 public static <T> void fill(List<? super T> list, T obj ...
- javascript(JQuery)元素操作
html代码如下: <div id="picK"> <ul> <li style="float:left;width:90px;" ...
- 安装notepad++ in ubuntu16.04
一.安装notepad++ Ubuntu下的安装方法: sudo add-apt-repository ppa:notepadqq-team/notepadqq sudo apt-get update ...