如何测试是否设置了变量? [英] How to test if a variable is set?

查看:33
本文介绍了如何测试是否设置了变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 PHP 中,有一个 isset 函数.爪哇呢?我想我可以将 == null 与对象一起使用,但是像 int

In PHP, there is a isset function. What about Java? I think I can use == null with objects, but what about value types like int

推荐答案

Java 的编译器不会让你定义变量并在它们被赋值之前使用它们,所以问题不会以与存在的形式相同的形式存在在 php 中.

Java's compiler won't let you define variables and use them before they were assigned a value, so the problem doesn't exist in the same form as it exists in php.

如果在你的情况下编译器没有阻止你(因为这是一个实例变量),最好的解决方案可能是将变量初始化为一些特殊"Guest11239193 建议的值.像这样:

If in your case the compiler didn't stop you already (because this is eg an instance variable) the best solution is probably to initialize the variable to some "special" value as suggested by Guest11239193. Like this:

int x = 0; // because by convention 0 is a reasonable default here

当然,这是多么安全、合理"的事情啊!初始化值取决于应用程序.

Of course, what a "safe, reasonable" initialization value is depends on the application.

之后,你可以

if (x == 0) { // only allow setting if x has its initial value
    x = somenewvalue;
}

或者您可以通过禁止多次更改的 setter 访问 x(在大多数情况下可能会矫枉过正):

Or you could access x via a setter that inhibits changing more than once (probably overkill for most cases):

private int x;
private boolean x_was_touched = false;

public void setX (int newXvalue) {
    if (!x_was_touched) {
       x = newXvalue;
       x_was_touched = true;
    }
}

public int getX() {
    return x;
}

你也可以使用 Integer,int 的对象兄弟,它可以被初始化为 null

You could also use an Integer, int's object brother, which could be initialized to null

Integer x = null; 

然而,你认为你需要这些知识的事实可能会在你的程序中隐藏一个更深层次的逻辑缺陷,所以我建议你探索为什么你想知道一个原始值(原始值而不是对象,int vs Integer) 没有被触及.

However, the fact that you think you need that knowledge may hide a deeper logic flaw in your program, so I'd suggest you explore the reason why you want to know if a primitive value (primitive as opposed to objects, int vs Integer) wasn't touched.

这篇关于如何测试是否设置了变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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