java-验证字符串是否为正数,空/空字符串
作者:互联网
我有一个接受字符串clientid的方法,它具有以下要求:
> clientid可以是大于零的正数.但是,如果它是负数或零,则将IllegalArgumentException与消息一起抛出.
> clientid不能为null或空字符串.但是,如果是,则将IllegalArgumentException与消息一起抛出.
> clientid也可以是普通字符串.例如,它可以是abcdefgh或任何其他字符串.
import static com.google.common.base.Preconditions.checkArgument;
public Builder setClientId(String clientid) {
checkArgument(!Strings.isNullOrEmpty(clientid), "clientid cannot not be null or an empty string, found '%s'.",
clientid);
final Long id = Longs.tryParse(clientid);
if (id != null) {
checkArgument(id.longValue() > 0, "clientid must not be negative or zero, found '%s'.", clientid);
}
this.clientid = clientid;
return this;
}
此代码可以正常工作.现在的问题是,我不能使用版本11以上的番石榴库.如果我使用了它,那会对使用该库的客户造成问题,因此总之,我正在寻找这行的替代品long long = Longs.tryParse (clientid);不使用guava或可能使用较旧的guava版本11.因为Longs.tryParse方法是在Guava 14或更高版本中添加的.
最好的方法是什么?我们可以从Apache Commons使用什么?
解决方法:
我建议使用relocating classes的Apache Maven Shade Plugin重新包装Guava.简而言之,您可以将Guava中的软件包重命名为com.example.mypackage.com.google.common之类的名称,然后在项目中使用它们.
这样,您可以使用最新版本的Guava,而不会引起客户的依赖冲突.
这是一个基于jersey-repackaged-guava
的示例POM:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example.mypackage</groupId>
<artifactId>repackged-guava-example</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.3</version>
<inherited>true</inherited>
<configuration>
<minimizeJar>false</minimizeJar>
<createSourcesJar>true</createSourcesJar>
<shadeSourcesContent>true</shadeSourcesContent>
<artifactSet>
<includes>
<include>com.google.guava:guava:*</include>
</includes>
</artifactSet>
<relocations>
<relocation>
<pattern>com.google.common</pattern>
<shadedPattern>${repackaged.prefix}.com.google.common</shadedPattern>
</relocation>
<relocation>
<pattern>com.google.thirdparty</pattern>
<shadedPattern>${repackaged.prefix}.com.google.thirdparty</shadedPattern>
</relocation>
</relocations>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
<optional>true</optional>
</dependency>
</dependencies>
<properties>
<repackaged.prefix>com.example.mypackage</repackaged.prefix>
</properties>
</project>
然后依靠repackged-guava-example并更改您的导入:
import com.example.mypackage.com.google.common.primitives.Longs;
请注意,如果您在具有IDE的多模块项目中使用此功能,则需要配置IDE以忽略重新打包的模块的目标类(例如,参见https://youtrack.jetbrains.com/issue/IDEA-126596).否则,您的IDE将使用具有原始程序包名称的原始类,而不是重新打包的类.
标签:guava,apache-commons,preconditions,java 来源: https://codeday.me/bug/20191119/2033192.html