java中如何实现两个版本号(如5.7
vs 5.7.36
)怎么比较大小?
百度上用java 比较版本号
关键字搜索了一下都找到的文章都要自己写代码做字符串分割,分段比较。。。好麻烦。
bing/google
上搜索英文关键字java compare version
,第二个就是这篇在stackoverflow上的文章
https://stackoverflow.com/questions/198431/how-do-you-compare-two-version-strings-in-java
给出了最简单的现成的方案:使用org.apache.maven:maven-artifact:3.2.5
库中的
org.apache.maven.artifact.versioning.DefaultArtifactVersion
,比较版本号就变得很简单:
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
DefaultArtifactVersion minVersion = new DefaultArtifactVersion("1.0.1");
DefaultArtifactVersion maxVersion = new DefaultArtifactVersion("1.10");
DefaultArtifactVersion version = new DefaultArtifactVersion("1.11");
if (version.compareTo(minVersion) < 0 || version.compareTo(maxVersion) > 0) {
System.out.println("Sorry, your version is unsupported");
}
下面是我基于org.apache.maven.artifact.versioning.DefaultArtifactVersion
实现的用于JDBC检查数据库类型和版本号的方法:
import static com.google.common.base.Preconditions.checkState;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
/**
* JDBC工具类
* @author guyadong
*
*/
public class JDBCUtility {
/**
* 检查数据库类型及版本是否满足要求,不满足则抛出异常
* @param metaData
* @param requiredProductName 要求的数据库名,such as 'MySQL'
* @param requiredMinVersion 要求的数据最低版本号,such as '5.7.36'
* @param requiredMaxVersion 要求的数据最高版本号,为{@code null}或空忽略
* @throws SQLException 从DatabaseMetaData读取数据异常
*/
public static void checkDatatbaseVersion(DatabaseMetaData metaData,String requiredProductName,String requiredMinVersion,String requiredMaxVersion) throws SQLException{
String productName = checkNotNull(metaData,"metaData is null").getDatabaseProductName();
DefaultArtifactVersion minVersion = new DefaultArtifactVersion(checkNotNull(requiredMinVersion,"requiredMinVersion is null"));
DefaultArtifactVersion version = new DefaultArtifactVersion(metaData.getDatabaseProductVersion());
checkState(productName.equals(requiredProductName),"%s required",requiredMinVersion);
checkState(version.compareTo(minVersion) >= 0,"Sorry, %s min version %s is required",requiredProductName,minVersion);
if(!Strings.isNullOrEmpty(requiredMaxVersion)){
DefaultArtifactVersion maxVersion = new DefaultArtifactVersion(requiredMaxVersion);
checkState(version.compareTo(maxVersion) <= 0,"Sorry, %s max version %s is required",requiredProductName,maxVersion);
}
}
}
调用示例:
代码语言:javascript复制import java.sql.Connection;
// 创建数据库连接
Connection con=........;
JDBCUtility.checkDatatbaseVersion(con.getMetaData(),"MySQL","5.7",null);
参考资料
《How do you compare two version Strings in Java?》