java 扫描类_Java扫描指定包中所有类
1. 扫描类
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import com.cnp.andromeda.common.util.StringUtil;
/**
* @Author
* @Description 包扫描器
* @CopyRight
*/
public class ClassScanner{
private Map> classes = new HashMap>();
private FilenameFilter javaClassFilter; // 类文件过滤器,只扫描一级类
private final String CLASS_FILE_SUFFIX = ".class"; // Java字节码文件后缀
private String packPrefix; // 包路径根路劲
public ClassScanner(){
javaClassFilter = new FilenameFilter(){
@Override
public boolean accept(File dir, String name){
// 排除内部内
return !name.contains("$");
}
};
}
/**
* @Title: scanning
* @Description 扫描指定包(本地)
* @param basePath 包所在的根路径
* @param packagePath 目标包路径
* @return Integer 被扫描到的类的数量
* @throws ClassNotFoundException
*/
public Integer scanning(String basePath, String packagePath) throws ClassNotFoundException{
packPrefix = basePath;
String packTmp = packagePath.replace('.', '/');
File dir = new File(basePath, packTmp);
// 不是文件夹
if(dir.isDirectory()){
scan0(dir);
}
return classes.size();
}
/**
* @Title: scanning
* @Description 扫描指定包, Jar或本地
* @param packagePath 包路径
* @param recursive 是否扫描子包
* @return Integer 类数量
*/
public Integer scanning(String packagePath, boolean recursive){
Enumeration dir;
String filePackPath = packagePath.replace('.', '/');
try{
// 得到指定路径中所有的资源文件
dir = Thread.currentThread().getContextClassLoader().getResources(filePackPath);
packPrefix = Thread.currentThread().getContextClassLoader().getResource("").getPath();
if(System.getProperty("file.separator").equals("\\")){
packPrefix = packPrefix.substring(1);
}
// 遍历资源文件
while(dir.hasMoreElements()){
URL url = dir.nextElement();
String protocol = url.getProtocol();
if("file".equals(protocol)){
File file = new File(url.getPath().substring(1));
scan0(file);
} else if("jar".equals(protocol)){
scanJ(url, recursive);
}
}
}
catch(Exception e){
throw new RuntimeException(e);
}
return classes.size();
}
/**
* @Title: scanJ
* @Description 扫描Jar包下所有class
* @param url jar-url路径
* @param recursive 是否递归遍历子包
* @throws IOException
* @throws ClassNotFoundException
*/
private void scanJ(URL url, boolean recursive) throws IOException, ClassNotFoundException{
JarURLConnection jarURLConnection = (JarURLConnection)url.openConnection();
JarFile jarFile = jarURLConnection.getJarFile();
// 遍历Jar包
Enumeration entries = jarFile.entries();
while(entries.hasMoreElements()){
JarEntry jarEntry = (JarEntry)entries.nextElement();
String fileName = jarEntry.getName();
if (jarEntry.isDirectory()) {
if (recursive) {
}
continue;
}
// .class
if(fileName.endsWith(CLASS_FILE_SUFFIX)){
String className = fileName.substring(0, fileName.indexOf('.')).replace('/', '.');
classes.put(className, Class.forName(className));
}
}
}
/**
* @Title: scan0
* @Description 执行扫描
* @param dir Java包文件夹
* @throws ClassNotFoundException
*/
private void scan0(File dir) throws ClassNotFoundException{
File[] fs = dir.listFiles(javaClassFilter);
for(int i = 0; fs != null && i < fs.length; i++){
File f = fs[i];
String path = f.getAbsolutePath();
// 跳过其他文件
if(path.endsWith(CLASS_FILE_SUFFIX)){
String className = StringUtil.getPackageByPath(f, packPrefix); // 获取包名
classes.put(className, Class.forName(className));
}
}
}
/**
* @Title: getClasses
* @Description 获取包中所有类
* @return Map<String,Class<?>> K:类全名, V:Class字节码
*/
public Map> getClasses(){
return classes;
}
public static void main(String[] args) throws ClassNotFoundException{
ClassScanner cs = new ClassScanner();
int c = cs.scanning("W:/IWiFI/Code/trunk/operation/target/classes/", "com/cnp/andromeda/common/util/");
System.out.println(c);
System.out.println(cs.getClasses().keySet());
ClassScanner cs2 = new ClassScanner();
int c2 = cs2.scanning("com.cnp.swarm", false);
System.out.println(c2);
System.out.println(cs2.getClasses().keySet());
}
}
2. 依赖工具类
import java.io.File;
/**
* @FileName: StringUtil.java
* @Author
* @Description:
* @Date 2014年11月16日 上午10:04:03
* @CopyRight
*/
/**
* 字符串工具类
*/
public final class StringUtil {
/**
* @Title: getMethodName
* @Description: 获取对象类型属性的get方法名
* @param propertyName
* 属性名
* @return String "get"开头且参数(propertyName)值首字母大写的字符串
*/
public static String convertToReflectGetMethod(String propertyName) {
return "get" + toFirstUpChar(propertyName);
}
/**
* @Title: convertToReflectSetMethod
* @Description: 获取对象类型属性的set方法名
* @param propertyName
* 属性名
* @return String "set"开头且参数(propertyName)值首字母大写的字符串
*/
public static String convertToReflectSetMethod(String propertyName) {
return "set" + toFirstUpChar(propertyName);
}
/**
* @Title: toFirstUpChar
* @Description: 将字符串的首字母大写
* @param target
* 目标字符串
* @return String 首字母大写的字符串
*/
public static String toFirstUpChar(String target) {
StringBuilder sb = new StringBuilder(target);
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
return sb.toString();
}
/**
* @Title: getFileSuffixName
* @Description: 获取文件名后缀
* @param fileName
* 文件名
* @return String 文件名后缀。如:jpg
*/
public static String getFileSuffixName(String fileName) {
return fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
}
/**
*
* @Title: checkStringIsNotEmpty
* @Description:验证字符串是否不为空
* @param stringValue
* 传入要验证的字符串
* @return boolean true:不为 空 或 不为null; false:值为 空 或 为null
*/
public static boolean isNotEmpty(String stringValue) {
if (null == stringValue || "".equals(stringValue.trim())) {
return false;
}
return true;
}
/**
* @Title: getPackageByPath
* @Description 通过指定文件获取类全名
* @param classFile 类文件
* @return String 类全名
*/
public static String getPackageByPath(File classFile, String exclude){
if(classFile == null || classFile.isDirectory()){
return null;
}
String path = classFile.getAbsolutePath().replace('\\', '/');
path = path.substring(path.indexOf(exclude) + exclude.length()).replace('/', '.');
if(path.startsWith(".")){
path = path.substring(1);
}
if(path.endsWith(".")){
path = path.substring(0, path.length() - 1);
}
return path.substring(0, path.lastIndexOf('.'));
}
}
java 扫描类_Java扫描指定包中所有类相关推荐
- java import lang_要使用lang包中的类,必须用import语句将java.lang程序包引入到源程序。...
要使用l用it语源程科目汇总表账务处理程序的优点是( ). 摄影是做"减法"的,包必须包引画面上跟主题无关的物体越少越好. 流体包裹体相对于成岩矿物的相互叠置和结构位置关系,程序可 ...
- idea Cannot Resolve Symbol 不能找到别的包中的类 能找到自己包中的类
所以项目路径中不要出现"."
- java缺省包详解_Java在其它包中无法引用缺省包中的类
1.现象 1.1 问题场景 最近,在写测试代码时,将一个类(这里暂且称为ClassA)放在在缺省包中,也就是说,直接放在了src目录下,没有创建包.然后,将这个类打入了jar文件,提供给另外的工程(这 ...
- java调用包中的类_java调用另一个包中的类的方法
java调用另一个包中的类的方法 发布时间:2020-05-18 15:04:40 来源:亿速云 阅读:199 作者:小新 今天小编给大家分享的是java调用另一个包中的类的方法,相信很多人都不太了解 ...
- java byte 拓展_Java项目中如何扩展第三方jar包中的类?
有些时候你对第三方得到jar包中的类并不是很满意,想根据实际情况做一些扩展.如果说第三方的jar包已经提供了一些可扩展的类,比如提供了Interceptor,Filter或者其他的类,那么使用原生的比 ...
- java面试题43要使某个类能被同一个包中的其他类访问,但不能被这个包以外的类访问,可以( )
java面试题43要使某个类能被同一个包中的其他类访问,但不能被这个包以外的类访问,可以( ) A让该类不使用任何关键字 B使用private关键字 C 使用protected关键字 D 使用void ...
- Java遍历包中所有类包括jar包(完整转载)
第一部分转自 :http://blog.csdn.net/wangpeng047/article/details/8124390 第二部分转自:http://blog.csdn.net/wangpen ...
- Java遍历包中所有类
由于项目需要,我想获得某包下所有的类(包括该包的所有子包),从网上找了找,没有什么能用的,即使找到了写的也不怎样,效率低下.索性就自己写吧,正好也锻炼锻炼写代码的功底.特此分享出来,希望能帮到大家.. ...
- Java遍历包中所有类-终续
上一篇中,我向大家讲述了遍历jar包时所遇到的困难,本篇将向大家分享最终版代码. package com.itkt.mtravel.hotel.util;import java.io.File; im ...
最新文章
- 日记 [2008年01月21日]
- Python代码中的if __name__ == ‘__main__‘的作用是什么?
- ubuntu18.04安装gcc7.3.0g++7.3.0
- PHP 使用 OSS 批量删除图片
- 记一次线上服务假死排查过程
- Linux命令之basename 命令
- 《哪吒》票房超25亿元 进入中国电影票房总榜前十
- 不想跑滴滴,如何利用汽车赚钱?
- 光伏机器人最前线_高工机器人走进光伏:数字化车间未来可期
- PHP设计模式——职责链模式
- 一文把三个经典求和问题吃的透透滴。
- asp.net页面生命周期之页面的终结阶段
- Centos 6让SVN提交文件自动更新到nginx的WEB目录
- python条件、循环、终止
- 实验中常用光纤接头型号
- godaddy服务器内网站转移,2021年Godaddy最新域名转出教程 | Godaddy美国主机中文指南...
- Kattis - bumped B - Bumped! (最短路)
- win10无法安装提示磁盘布局不受UEFI固件支持的解决方法
- 厦大计算机科学系培养方案,厦门大学计算机科学系本科生课程方案.doc
- c语言股价连续上涨的天数,为什么通达信没有连涨天数,我的通达信怎么没有连涨天数显示...
热门文章
- vb中picturebox透明时看到下面的picturebox中图片
- java免费游戏,java – 分配免费游戏
- C#中Lambda表达式动态拼接生成工具类
- 机器学习统计学相关书籍
- itext pdf转图片_图片转PDF怎么转换?可以试试这个PDF转换软件
- python61到08使用说明书_python 08 文件操作
- php三级分销系统制作_微分销商城系统创建三级微商分销体系方法
- mysql 命令desc tables_oracle中与mysql中的命令 show databases, show tables, desc table类似的命令集...
- linux批量部署war工具,Linux 批量一键部署工具 Expect
- html怎么加断点快捷键,HTML添加断点 - osc_vyztkm1b的个人空间 - OSCHINA - 中文开源技术交流社区...