Maven project 中,运行时获取某依赖的版本号
<dependency> <groupId>cn.xs</groupId> <artifactId>qishi-api</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency>
// D:\mvnrepository\cn\xs\qishi-api\0.0.1-SNAPSHOT\qishi-api-0.0.1-SNAPSHOT.jar
String version = null; String[] jars = System.getProperty("java.class.path").split(";"); for (String jarpath : jars) { if(!jarpath.endsWith(".jar")) { continue; } File jarfile = new File(jarpath); if(jarfile.isDirectory()) { continue; } String name = jarfile.getName(); if(name.startsWith("qishi-api-")) { version = name.replace("qishi-api-", "").replace(".jar", ""); } }
得到的结果是:0.0.1-SNAPSHOT
如果是通过源码形式引入,则无法获取(开发过程中,该依赖项目在Eclipse中打开了,classpath 以源码形式引用)