我有一个使用旧Cassandra驱动程序库的项目,该库依赖于已在版本20中删除的不再使用的番石榴特征。我正在考虑添加一个测试,当有人不小心将Guava版本从19增加到20检测使用哪种Guava版本?
如何以编程方式找出使用哪种Guava版本?
我有一个使用旧Cassandra驱动程序库的项目,该库依赖于已在版本20中删除的不再使用的番石榴特征。我正在考虑添加一个测试,当有人不小心将Guava版本从19增加到20检测使用哪种Guava版本?
如何以编程方式找出使用哪种Guava版本?
我没有找到一个简单的方法来获得访问的版本,但在这里是为我工作的解决方案:
@Test(expected = ClassNotFoundException.class)
public void mustNotUpgradeToGuava20_asItIsIncompatibleWithCassandra() throws ClassNotFoundException {
Class.forName("com.google.common.graph.Graph");
}
该测试通过最多番石榴19和将失败,番石榴20。 Graph
类是我在发行说明中找到的第一批添加的类。
您可以从guava.jar中的META-INF /下的文件中获取版本字符串。在运行时,您需要使用适当的ClassLoader
实例来加载所需的META-INF /文件。您可以使用Guava的Resources
实用程序类直接加载具有唯一名称的资源,也可以使用$someGuavaClassName.class.getClassLoader().getResources(String)
在多个jar
文件中迭代同名资源。如果你使用后者,那么你将需要使用someGuavaClassName
,该版本将存在于您正在测试的版本中。 Resources
本身从1.0开始就已经在番石榴了,我不认为它很快就会去任何地方,所以应该是一个安全的类。
我在番石榴20.0和12.0上测试了以下内容,它对两者都有效。我怀疑它会为所有相对较新的版本番石榴的工作:
public class GuavaVersionFetcher {
public static void main(String... args) throws IOException {
System.out.println(determineGuavaMavenVersion());
System.out.println(determineGuavaManifestVersion());
}
public static String determineGuavaMavenVersion() throws IOException {
String resourceName = "META-INF/maven/com.google.guava/guava/pom.properties";
Properties properties = new Properties();
try (InputStream inputStream = Resources.getResource(resourceName).openStream()) {
properties.load(inputStream);
}
return properties.getProperty("version");
}
public static String determineGuavaManifestVersion() throws IOException {
Enumeration<URL> resources = Resources.class.getClassLoader()
.getResources("META-INF/MANIFEST.MF");
while (resources.hasMoreElements()) {
Manifest manifest;
try (InputStream inputStream = resources.nextElement().openStream()) {
manifest = new Manifest(inputStream);
}
Attributes mainAttributes = manifest.getMainAttributes();
String symbolicName = mainAttributes.getValue("Bundle-SymbolicName");
if ("com.google.guava".equals(symbolicName)) {
return mainAttributes.getValue("Bundle-Version");
}
}
return null;
}
}
输出示例:
20.0
20.0.0
注意:如果番石榴队曾经使用Maven的第一种方法移开可能不再工作等等我建议使用清单方法。