繁体   English   中英

为 java 中的变量添加约束

[英]add constraint for variables in java

如果新对象的属性必须满足一定条件,我可以直接对变量添加约束,使其无法创建新的object。 以下部分,我希望自动检查下界<=上界。 或其他类似 int lowerBound 的东西大于 0。在数据库中,我们有检查约束。 所以我想知道 Java:

import java.math.*;

public class SumAverageRunningInt {
    private int lowerBound;
    private int upperBound; 

    public SumAverageRunningInt(int lowerBound, int upperBound) {
        this.lowerBound = lowerBound;
        this.upperBound = upperBound;
    }


    public int getlowerBound() {return lowerBound;}
    public int getupperBound() {return upperBound;}
    

    public int sum() {
        int sum = 0;
        int i = 0;
        int a = this.getlowerBound();
        int b = this.getupperBound();
        while (a<=b) {
            sum = a + sum;
            a = a + 1;}
        return sum;
       }    
}

看看 Guava 中的前提条件class。

添加此依赖项:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>29.0-jre</version>
</dependency>

然后像这样使用它:

import static com.google.common.base.Preconditions.checkArgument;

public SumAverageRunningInt(int lowerBound, int upperBound) {
    checkArgument(lowerBound <= upperBound, "lowerBound should be smaller or equal than upperBound");
    this.lowerBound = lowerBound;
    this.upperBound = upperBound;
}

如果您不想添加第三方库(对于这样的小任务实际上没有必要),您可以自己实现检查:

public static void checkCondition(boolean condition, String errorMessage) {
    if (!condition) {
        throw new IllegalArgumentException(errorMessage);
    }
}

public SumAverageRunningInt(int lowerBound, int upperBound) {
    checkCondition(lowerBound <= upperBound, "lowerBound should be smaller or equal than upperBound");
    this.lowerBound = lowerBound;
    this.upperBound = upperBound;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM