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<String, Class<?>> classes = new HashMap<String, Class<?>>(); 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<URL> 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<JarEntry> 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<String, Class<?>> 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('.')); } }
相关推荐
资源分数必须最少填1,不好意思。如果没有积分可以去git链接下载,本人博客有git地址。博客地址:... java 遍历指定包下所有类,返回完整类名。工具类,可以直接拷入使用。
主要介绍了Java实现从jar包中读取指定文件的方法,涉及java针对jar文件的读取及查找相关操作技巧,需要的朋友可以参考下
NULL 博文链接:https://mrpengpengda.iteye.com/blog/1536292
java.io包中的File类.doc
整合了java.awt.*;java.awt.event.*;javax.swing.*包中的类,结合布局与事件处理....这是本人自己写的哦
springboot 项目编译后无法扫描加载到子jar包中的注解解决方法
java反射jar包中class,并可进行文件比较
扫描出指定包下所有的类名。 Quick Start 指定包名: PkgScanner scanner = new PkgScanner("cn.fh.pkgscanner"); List<String> list = scanner.scan(); list.forEach( f -> System.out.println(f)); 输出结果: ...
Java标准包中基本常用类和方法.docx
java 扫描TCP端口 java 扫描TCP端口 java 扫描TCP端口
本Java精华内容深入Java API、嵌套类和内部类、与时间有关的类Date,DateFormat,Calendar、文件与流、Java变量类型间的相互转换、Java与Web、用连接池提高Servlet访问数据库的效率、Java扩展、应用服务器的集群策略及...
java实现class的热替换
java IO 类层次图,以清晰明了的形式标明了java io中各种类的关系
包是由.class文件组成的一个集合,.class文件时可以用Java...包是一种松散的概念,一般情况下,功能相同或者相关的类组织在一个包中,例如java.io包中的类都与输入、输出有关,java.applet包中的类都与applet程序有关。
主要介绍了如何将java打包成可执行的jar,并执行jar包中指定的main方法的相关资料,文中给出了详细的示例代码,对大家具有一定的参考价值,需要的朋友们下面来一起看看吧。
本工具用于在jar包中查找类,手动查找很麻烦,这个很小的工具很好的帮助你!
数据库课程设计计算器——主要实现四则混和运算,简单科学计算,数制间转换,获取... 数据结构:堆栈(使用JAVA中util包中Stack类) 列表(使用JAVA中util包中ArrayList类) 界面良好,代码完整可直接运行,文档很好哦!
TestJTwain.java,ScanTwice.java,DemoFrame.java,DemoADF.java,DemoFrame.java,DemoGetCapabilities.java,DemoHiddenUI.java,ImageDisplayer.java,DemoSaveJPEG.java等等一系列扫描仪功能,所有的.java文件...
java-android面试题
用Java写的一个小巧程序,局域网内,扫描开放指定端口的主机