java运行中获取类的包版本

2023-03-02  本文已影响0人  holyABCD

java运行中获取类的包版本

方法

java运行中获取类的包版本 AlphabetConverter.class 换成需要获取包版本的包内的任一类

String fileFullPath = AlphabetConverter.class.getProtectionDomain().getCodeSource().getLocation().getFile();
//本地运行,获取的内容如下  /Users/cn/.m2/repository/org/apache/commons/commons-text/1.6/commons-text-1.6.jar
if(fileFullPath == null || fileFullPath.length() == 0){
  throw new RuntimeException("getProtectionDomain().getCodeSource().getLocation().getFile() get null!");
}

String jarVersion = fileFullPath.substring(fileFullPath.lastIndexOf("/")).replace("包artifactId","").replace(".jar","");

用处

给使用方提供了一个功能jar包,该jar包会定时从服务端获取数据,随着jar包升级,使用方增多,会使得服务方对于调用方jar包版本,jar功能把控降低。
于是需要一个jar包通知机制/上报机制:jar通过上报接口定时通知服务端目前使用方名称、jar包版本等信息
通过此功能可自动识别jar版本

上一篇 下一篇

猜你喜欢

热点阅读