Java:重载 java.lang.Number 的(通用)方法

发布于 2024-12-14 05:21:27 字数 3543 浏览 0 评论 0原文

所以我读了这里关于数字的讨论,因为我有一个类似的问题。 就我而言,我希望能够对数字进行数学运算。我的想法是编写一个不可变的“RealNumber”类来处理原始数字(整数、长整型、浮点型和双精度型),而不需要一堆instanceof 控件。有人提到重载方法并让编译器完成工作。
这是我的第一次尝试:

简单的 TestClass:

public class Test {
public static void main(String[] args) {
    RealNumber<Double> d = RealNumber.create(3.4);
    d.add(4.7);
    }
}

RealNumber 类:(请在注释中提及方法),

public class RealNumber<N extends Number> extends Number{

    N number;   

    private RealNumber(N number){
        if (number == null){
            throw new NullPointerException("number is null");
        }
        this.number = number;
    }

    public N get(){
        return number;
    }

    //note this Method
    public RealNumber<N> add(N number){
        return add(number);
    }

    private RealNumber<Integer> add(Integer number){
        return new RealNumber<Integer>(intValue() + number);
    }

    private RealNumber<Long> add(Long number){
        return new RealNumber<Long>(longValue() + number);
    }

    private RealNumber<Float> add(Float number){
        return new RealNumber<Float>(floatValue() + number);
    }

    private RealNumber<Double> add(Double number){
        return new RealNumber<Double>(doubleValue() + number);
    }

    @Override
    public int intValue() {
        return number.intValue();
    }

    @Override
    public long longValue() {
        return number.longValue();
    }

    @Override
    public float floatValue() {
        return number.floatValue();
    }

    @Override
    public double doubleValue() {
        return number.doubleValue();
    }


    public static final RealNumber<Integer> create(Integer number){
        return new RealNumber<Integer>(number);
    }

    public static final RealNumber<Long> create(Long number){
        return new RealNumber<Long>(number);
    }

    public static final RealNumber<Float> create(Float number){
        return new RealNumber<Float>(number);
    }

    public static final RealNumber<Double> create(Double number){
        return new RealNumber<Double>(number);
    }
}

因此第一个测试导致我出现 StackOverflowError,因为方法“add”总是调用自身。

第二次尝试(仅更改了方法)

public RealNumber<N> add(Number number){
    return add(number);
}

第一次没有那么好,因为它允许添加 BigDecimals 或布尔值等其他内容,第二次尝试导致我遇到相同的 StackOverflowError。所以我改变了:

public RealNumber<N> add(N number){
    return add(number);
}

//note the public here
public RealNumber<Double> add(Double number){
    return new RealNumber<Double>(doubleValue() + number);
}
//... public RealNumber<Integer, Long, Float> add....

在我的 TestClass 中无法编译 -> “方法 add(Double) 对于类型 RealNumber 来说不明确
最后这有效了:

public RealNumber<N> add(Number number){
    return add(number);
}

//note the public here
public RealNumber<Double> add(Double number){
    return new RealNumber<Double>(doubleValue() + number);
}
//... public RealNumber<Integer, Long, Float> add....

但又带来了两个问题:此模式允许将 Double 添加到 Ints (这会导致 Integer 的 RealNumber ),并且如果传递 BigInteger、Byte 或其他一些 Number ,则会导致 StackOverflowError 。

所以我的主要问题是:

如果每个 add 方法都是公共的,为什么编译器会在 Test.class 中选择正确的方法,如果它们是私有的,那么编译器会失败。

我可以做什么来解决这些问题?

So I read discussion about Numbers here, because I have a similar Problem.
In my case, I wanna be able to allow mathematical operations on Numbers. My idea was to write an immutable ´RealNumber´ class that handles primitive Numbers (Integer, Long, Float and Double), without a bunch of instanceof controls. Someone mentioned to Overload Methods and let the compiler do the work.
This was my first attempt:

simple TestClass:

public class Test {
public static void main(String[] args) {
    RealNumber<Double> d = RealNumber.create(3.4);
    d.add(4.7);
    }
}

RealNumber class: (please mention the Method with the comment)

public class RealNumber<N extends Number> extends Number{

    N number;   

    private RealNumber(N number){
        if (number == null){
            throw new NullPointerException("number is null");
        }
        this.number = number;
    }

    public N get(){
        return number;
    }

    //note this Method
    public RealNumber<N> add(N number){
        return add(number);
    }

    private RealNumber<Integer> add(Integer number){
        return new RealNumber<Integer>(intValue() + number);
    }

    private RealNumber<Long> add(Long number){
        return new RealNumber<Long>(longValue() + number);
    }

    private RealNumber<Float> add(Float number){
        return new RealNumber<Float>(floatValue() + number);
    }

    private RealNumber<Double> add(Double number){
        return new RealNumber<Double>(doubleValue() + number);
    }

    @Override
    public int intValue() {
        return number.intValue();
    }

    @Override
    public long longValue() {
        return number.longValue();
    }

    @Override
    public float floatValue() {
        return number.floatValue();
    }

    @Override
    public double doubleValue() {
        return number.doubleValue();
    }


    public static final RealNumber<Integer> create(Integer number){
        return new RealNumber<Integer>(number);
    }

    public static final RealNumber<Long> create(Long number){
        return new RealNumber<Long>(number);
    }

    public static final RealNumber<Float> create(Float number){
        return new RealNumber<Float>(number);
    }

    public static final RealNumber<Double> create(Double number){
        return new RealNumber<Double>(number);
    }
}

so the first test leads me to a StackOverflowError, because the method ´add´ always calls itself.

second try (only changed methods)

public RealNumber<N> add(Number number){
    return add(number);
}

first wasn't as good, cause it will allow to add BigDecimals, or other things like Boolean, and second leads me to the same StackOverflowError. so I changed:

public RealNumber<N> add(N number){
    return add(number);
}

//note the public here
public RealNumber<Double> add(Double number){
    return new RealNumber<Double>(doubleValue() + number);
}
//... public RealNumber<Integer, Long, Float> add....

which fails to compile in my TestClass -> "The Method add(Double) is ambiguous for the Type RealNumber
finally this worked:

public RealNumber<N> add(Number number){
    return add(number);
}

//note the public here
public RealNumber<Double> add(Double number){
    return new RealNumber<Double>(doubleValue() + number);
}
//... public RealNumber<Integer, Long, Float> add....

but brings another 2 issues: this pattern allows to add Doubles to Ints (which results in RealNumber of Integer ), and results in a StackOverflowError if one passes a BigInteger, Byte or some other Number.

So my main questions:

Why the compiler chooses the right method in Test.class if every add Method is public and fails, if they are private.

What can I do to fix the issues?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

瞎闹 2024-12-21 05:21:27

[抱歉,我第一次尝试时没有完全理解这个问题。 ]

我认为@Rafael 这里没有一个简单的答案,因为正如@Andrei Bodnarescu 指出的那样,类型擦除意味着您在运行时没有 N 参数的类型。我认为您必须为 Number 的每个子类提供 add() 方法的具体实现。

public RealNumber<Integer> add(Integer number) {
    return new RealNumber<Integer>(intValue() + number);
}
public RealNumber<Long> add(Long number) {
    return new RealNumber<Long>(longValue() + number);
}

如果您不想将整数添加到双精度数中,那么我想您将需要执行以下操作:

public RealNumber<Integer> add(Integer number){
    if (!(this instanceof Integer)) {
        throw new IllegalArgumentException("You can't do this...");
    }
    return new RealNumber<Integer>(intValue() + number);
}

我没有看到任何简单的方法来解决此问题。

[ Sorry, I didn't fully understand the question with my first try. ]

I don't think there is an easy answer here @Rafael because as @Andrei Bodnarescu pointed out, type erasure means that you do not have the type of your N parameter at runtime. I think you have to provide a concrete implementation of your add() method for each subclass of Number.

public RealNumber<Integer> add(Integer number) {
    return new RealNumber<Integer>(intValue() + number);
}
public RealNumber<Long> add(Long number) {
    return new RealNumber<Long>(longValue() + number);
}

If you don't want to add integers to doubles then I guess you will need to do something like:

public RealNumber<Integer> add(Integer number){
    if (!(this instanceof Integer)) {
        throw new IllegalArgumentException("You can't do this...");
    }
    return new RealNumber<Integer>(intValue() + number);
}

I don't see any easy way to work around this.

无所谓啦 2024-12-21 05:21:27

由于类型擦除, :

public RealNumber<N> add(N number){
        return add(number);
    }

方法总是调用自身:在 Java 中,泛型仅用于编译时,它们在运行时不再存在,因此 VM 实际上不知道 N 是什么类型,因此它调用可用的最通用的方法,即这个。您还必须将类型作为 Class 作为参数传递给方法,如下所示:

public RealNumber<N> add(N number,Class<N> numberClass){
        return add(number);
    }

The :

public RealNumber<N> add(N number){
        return add(number);
    }

method always calls itself because of type erasure: in Java generics are only for compile time, they're no longer present at runtime, so the VM effectively doesn't know what type N is, so it calls the most generic methods available, namely this one. You must pass the type as Class as argument to the method aswell, something like:

public RealNumber<N> add(N number,Class<N> numberClass){
        return add(number);
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文