如何在Java中更改变量的类型?

How to Change the Type of a Variable in Java?

提问人:poma12390 提问时间:11/9/2023 更新时间:11/9/2023 访问量:99

问:

我正在处理一个 Java 项目,遇到了需要在运行时更改变量类型的情况。有没有办法在 Java 中做到这一点?

void doSmth(){
        String var = "13";
        //some work with string;
        int var = -1;
        //continue program
    }

在我的代码后面,我需要将 var 视为不同的类型,比如 int 或 double。有没有办法在不导致类型不匹配错误的情况下实现这一点?

void doSmth(){
    String var = "13";
    //some work with string
    var=null;
    int var = -1;
    //continue program
}
Main.java:15: error: variable var is already defined in method doSmth()
        int s = -1;
Java 变量 类型

评论

0赞 Jean-Baptiste Yunès 11/9/2023
你不能,Java 是强类型的:变量链接到类型。
0赞 Sam Daniel 11/9/2023
正如其他人所说,您不能对作用域中的不同类型重复使用相同的变量名称。我想知道您试图通过重用变量名称来解决什么用例?

答:

1赞 Marco 11/9/2023 #1

不能将变量重新定义为具有相同名称的其他类型。 您可以使用 Integer 类方法来解析“数字”字符串。

int newVariable = Integer.valueOf(var);

顺便说一句,改变类型称为“铸造”。 如果你想像这样改变类型,你可以寻找“cast String to int Java”

评论

0赞 user85421 11/9/2023
Integer.valueOf()不是解析字符串的最佳选择,它 get an - 它将创建一个实例,然后将其转换为 - 避免这些中间步骤和对象intIntegerintInteger.parseInt()
1赞 rg8443 11/9/2023 #2

Java 中没有 Variant 或 Union 类型,但您可以使用 Object。

像这样:

class Scratch {
    public static void main( String[] args ) {
        Object o = "foo";
        System.out.println("o(" + o.getClass() + ") = " + o);
        o = -1;
        System.out.println("o(" + o.getClass() + ") = " + o);
    }
}

如果你真的只是想重用一个变量名,请使用 {} 来限定变量的范围:

class Scratch {
    public static void main( String[] args ) {
        {
            String var = "foo";
            System.out.println(var);
        }
        {
            int var = 1;
            System.out.println(var);
        }
    }
}
1赞 Flavian Diol D 11/9/2023 #3

Java 不是像 Python 或 JavaScript 那样的动态类型语言。它是一种强类型语言,这意味着每个变量都有一个与之关联的类型,一旦声明为类型,就无法在运行时更改。

您绝对可以创建一个新变量来提取存储在变量中的当前值,有许多工厂方法可以做到这一点。

void doSmth(){
    String var = "13";
    //some work with string;
    int var = -1;
    //continue program
}

据我所知,您的 var 只处理哪些数字最初是 String 类型,然后您希望将其继续作为 int 类型,以便这样做。您可以尝试这样做

void doSmth(){
    String var = "13";
    //some work with var;
    int now = Integer.valueOf(var);
    //continue program
}

这里现在将当前值存储在 var 中,除非并且直到 var 具有数字以外的其他内容。

或者,如果您真的不想初始化一个新变量,而只想使用同一个变量,请尝试使用 Object 类型的变量。这是所有类的超类,因此它可以容纳任何类的对象。但这不是一个类型安全的措施,但如果它不是问题,你可以继续使用它。

void doSmth(){
    Object var = "13";
    //some work with string;
    var = -1;
    //continue program
}

如果您希望两个变量具有相同的名称,如果它们都在同一个范围内,这是不可能的,如果您想尝试类似的事情,请尝试更改变量范围。

评论

0赞 Flavian Diol D 11/9/2023
.valueOf() 返回一个 Integer 类型的对象,而不是如您提到的,Integer.parseInt() 也可以返回直接原语。它可以根据用例使用。
0赞 Rok T. 11/9/2023 #4

如前所述,Java 是强类型的,所以这种事情真的不可能以你想要的方式实现。

你可以创建一个对象,然后可以保存你想要的任何引用或值,但我强烈建议不要使用它 - 类型是你的朋友。

public static void main(String[] args) {
    Object obj;
    obj = 1;
    System.out.println(obj);
    obj = "asdsa";
    System.out.println(obj);
    obj = 2.0D;
    System.out.println(obj);
    obj = List.of("123", 23);
    System.out.println(obj);
}

将打印:

1
asdsa
2.0
[123, 23]
0赞 simsam 11/9/2023 #5

可悲的是,你不能。但这并不意味着你不能在变量之间传递值。在你的情况下,你有一个具有一定价值的。如果要对该字符串执行某些操作,然后将该字符串的值用于其他目的,则不能仅更改该变量的类型,还可以将字符串值转换为整数值并将其分配给另一个变量。例如:String var

void doSmth() {
    String var = "13";
    // you can do some work with this string
    // after you are done working with the string and the value of it changes
    // you may want to use that value in an integer calculation

    // lets say for the sake of this example your var = "2"
    var = "2";
    // to use the new value of var in another calculation you can change the data and assign it to a new variable
    int newVar = Integer.parseInt(var);
    // here you change the type of data and assign it to a new variable so newVar = 2
    // you can now continue working with this new variable.
}

这只是将一种数据类型转换为另一种数据类型的一个示例。但也许那不是你想做的。也许这两个变量没有在同一个算法中使用,你只是喜欢变量名称,或者它有意义。在 Java 中,变量在特定上下文中是“可见的”,而在该上下文之外是不可见的。这意味着,如果要将一个变量名称用于多个不同且不相关的计算,则可以编写函数来执行这些计算。让我们看另一个例子:

void doSmth() {
    String var = "13";
    // you can do some work with this string variable
} 
// after you are done with the string and you want to do something else and you want to keep the name, you can write up a new function
void doSmthElse() {
    int var = -1;
    // you can now do something else with var as within this functions context there exists only one variable named "var" and it is an integer type
}

如果你的变量以某种方式连接,并且你不想为了清楚起见而重命名它,你可以创建一个函数,将第一次出现的 var 传递给第二次。

void doSmthRelated() {
    String var = "13";
    // do something with var
    // now you want to use var for something else and you want to keep the two connected variables named the same way

    // call the new function and pass the string as an argument
    relatedFunct(var);

    // if you need to use the value returned by the related function inside this function,
    // you will need to assign the returned value to a variable that doesn't share the name
    int necessaryValue = relatedFunct2(var);
}

void relatedFunct(String argument) {
    // you can now convert the passed argument to the type you need
    int var = Integer.parseInt(argument);
    // do something with var
}

int relatedFunct2(String argument) {
    // convert the argument and do whatever you want with the new var
    int var = Integer.parseInt(argument);
    // do something with var

    // and return the value so you can use it further in your main function
    return var;
}

我希望这有助于消除类型、变量名称和上下文的一些混淆。

编辑:正如user85421指出的那样,这不是将a转换为.最好使用 .Integer.valueOf()StringintInteger.parseInt()