apache dubbo 2.7.3 源代码片段 - 获取类实现的版本号

18 篇文章 0 订阅
11 篇文章 0 订阅

 

// Dubbo implementation version, usually is jar version.
private static final String VERSION = getVersion(Version.class, "");

org.apache.dubbo.common.Version#getVersion(java.lang.Class<?>, java.lang.String)

public static String getVersion(Class<?> cls, String defaultVersion) {
    try {
        // find version info from MANIFEST.MF first
        Package pkg = cls.getPackage();
        String version = null;
        if (pkg != null) {
            version = pkg.getImplementationVersion();
            if (!StringUtils.isEmpty(version)) {
                return version;
            }

            version = pkg.getSpecificationVersion();
            if (!StringUtils.isEmpty(version)) {
                return version;
            }
        }

        // guess version fro jar file name if nothing's found from MANIFEST.MF
        CodeSource codeSource = cls.getProtectionDomain().getCodeSource();
        if (codeSource == null) {
            logger.info("No codeSource for class " + cls.getName() + " when getVersion, use default version " + defaultVersion);
            return defaultVersion;
        }

        String file = codeSource.getLocation().getFile();
        if (!StringUtils.isEmpty(file) && file.endsWith(".jar")) {
            version = getFromFile(file);
        }

        // return default version if no version info is found
        return StringUtils.isEmpty(version) ? defaultVersion : version;
    } catch (Throwable e) {
        // return default version when any exception is thrown
        logger.error("return default version, ignore exception " + e.getMessage(), e);
        return defaultVersion;
    }
}

/**
 * get version from file: path/to/group-module-x.y.z.jar, returns x.y.z
 */
private static String getFromFile(String file) {
    // remove suffix ".jar": "path/to/group-module-x.y.z"
    file = file.substring(0, file.length() - 4);

    // remove path: "group-module-x.y.z"
    int i = file.lastIndexOf('/');
    if (i >= 0) {
        file = file.substring(i + 1);
    }

    // remove group: "module-x.y.z"
    i = file.indexOf("-");
    if (i >= 0) {
        file = file.substring(i + 1);
    }

    // remove module: "x.y.z"
    while (file.length() > 0 && !Character.isDigit(file.charAt(0))) {
        i = file.indexOf("-");
        if (i >= 0) {
            file = file.substring(i + 1);
        } else {
            break;
        }
    }
    return file;
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值