从Object extends Number获取原始值? [英] Get primitive value from Object extends Number?

查看:167
本文介绍了从Object extends Number获取原始值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个类,可以处理减去,添加,更新给定类型的数字(扩展数字的任何东西)。

I am trying to make a class that can process subtracting, adding, updating for number with given type (anything that extends Number).

public class DynamicNumber<T extends Number> {

    private T number;

    public DynamicNumber(T number) {
        this.number = number;
    }

    public void add(T number) {
        this.number += number;
    }

    public void subtract(T number) {
        this.number -= number;
    }

}

这不起作用和抛出以下异常:

This won't work and throws the following exception:


对于参数类型(T,T),运算符+ =未定义

The operator += is undefined for the argument type(s) (T, T)

这是因为你不能将该运算符用于对象,也只能用于原始值。

This is because you can't use that operator for objects, and only on primitive values.

我的问题是如何在不知道确切类型的情况下获取给定对象的原始值,只知道它扩展了数字?

My question is how can I get the primitive value of the given object without knowing it's exact type, but just knowing it extends Number?

推荐答案

T总是扩展Object,而不是原始的。您可以使用instanceof然后强制转换为扩展Number的对象。之后 - 如果对象表示基元 - 您可以使用自动拆箱或使用显式转换来使用它。没有办法解决这个问题。

T always extends Object, never a primitive. You can use instanceof and then cast to the object that extends Number. After that - if the object represents a primitive - you can use it using auto unboxing or using an explicit conversion. There is no way around this.

这篇关于从Object extends Number获取原始值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆