简体   繁体   English

在Java中不指定原始类型就声明变量或将对象更改为其对应的原始类型

[英]Declaring a variable without specifying primitive type in Java OR changing an object to it's corresponding primitive type

I want to be able to declare a variable in Java, however I do not know what the type of the variable will be until an if, if else statement is evaluated. 我希望能够在Java中声明一个变量,但是在评估if,if else语句之前,我不知道变量的类型。

I know that you can't declare the variable within each if statement because it will be out of scope outside of the if statement. 我知道您不能在每个if语句中声明变量,因为它将超出if语句之外的范围。

The variable also MUST be a primitive datatype instead of an object (eg Integer, Double, String) 该变量还必须是原始数据类型,而不是对象(例如,Integer,Double,String)

// do not know datatype yet
(type) signalValue;

        // signal is Integer object
        if (SysjInput[1] instanceof Integer) {
                signalValue = (int) SysjInput[1];

        // signal is String object
        } else if (SysjInput[1] instanceof String) {
                signalValue = (String) SysjInput[1];

        // signal is Double object  
        } else if (SysjInput[1] instanceof Double) {
                signalValue = (double) SysjInput[1];
        }

System.out.println(signalValue)

I have also tried something like this: 我也尝试过这样的事情:

Object signalValue;
signalValue = 123;

It will convert it to an Integer object and I would need some way to convert it to a primitive type. 它将把它转换成Integer对象,我需要一些方法将它转换成原始类型。

Initializing with Object class should work, I tryed this and worked just fine: 使用Object类进行初始化应该可以工作,我尝试了一下并且工作得很好:

    public static void main(String[] args) {

    Object t;

    t = 4;
    int d = (int) t;
    int e = d + d;

    System.out.println(e);
}

output: 8 输出:8

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

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