如何在特殊情况下使用更简单的构造函数

ski*_*iwi 1 java object

我想知道我想要实现的是否实际上是可能的,我不知道我正在做什么的确切名称因此为什么我不能正确地谷歌搜索结果以及为什么这个主题标题也有点模糊.

我的课程:

AccountConstraint.java:

package dao.constraint;

public class AccountConstraint {
    private Range<Integer> accountId;
    private String username;
    private String password;
    private String email;

    public AccountConstraint(final Range<Integer> accountId, final String username, final String password, final String email) {
        this.accountId = accountId;
        this.username = username;
        this.password = password;
        this.email = email;
    }

    public Range<Integer> getAccountId() {
        return accountId;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public String getEmail() {
        return email;
    }
}
Run Code Online (Sandbox Code Playgroud)

Range.java:

package dao.constraint;

public class Range<T> {
    private T min;
    private T max;

    public Range(T min, T max) {
        this.min = min;
        this.max = max;
    }

    public T getMin() {
        return min;
    }

    public T getMax() {
        return max;
    }
}
Run Code Online (Sandbox Code Playgroud)

一个完全有效的代码示例是:

AccountConstraint ac = new AccountConstraint(new Range<Integer>(5, 10), null, null, null));
Run Code Online (Sandbox Code Playgroud)

如果您希望获得ID为5到10的所有帐户.仍然有效,但更奇怪的代码将是:

AccountConstraint ac = new AccountConstraint(new Range<Integer>(3, 3), null, null, null));
Run Code Online (Sandbox Code Playgroud)

如果你想获得身份3的帐户.

我想要的是:

AccountConstraint ac = new AccountConstraint(3, null, null, null);
Run Code Online (Sandbox Code Playgroud)

作为new Range<Integer>(3, 3)理论上等于3.

有没有办法做到这一点,可能通过添加代码到Range类,我觉得这应该是可能的,但我不知道如何和/或从哪里开始.

Mat*_*ens 5

你不需要对你的Range类做任何事情,只需提供另一个AccountConstraint构造函数,使其成为Range一个int:

public AccountConstraint(final int accountId, final String username, final String password, final String email) {
    this(new Range<Integer>(accountId, accountId), username, password, email);
}
Run Code Online (Sandbox Code Playgroud)