Programming

스위치에서 null을 사용하는 방법

procodes 2020. 5. 14. 20:56
반응형

스위치에서 null을 사용하는 방법


Integer i = ...

switch (i){
    case null:
        doSomething0();
        break;    
    }

위의 코드에서 switch case 문에 null을 사용할 수 없습니다. 어떻게 다르게 할 수 있습니까? default다른 것을하고 싶기 때문에 사용할 수 없습니다 .


switchJava 명령문에서는 불가능합니다 . 확인하기 null전에 switch:

if (i == null) {
    doSomething0();
} else {
    switch (i) {
    case 1:
        // ...
        break;
    }
}

switch명령문 *에 임의의 객체를 사용할 수 없습니다 . 컴파일러가 switch (i)어디에 있는지 i대해 불만을 제기하지 않는 이유 Integer는 Java가에서 Integerto를 자동으로 개봉하기 때문 int입니다. assylias가 이미 말했듯이, unboxing은 NullPointerException를 던질 것 i입니다 null.

* Java 7부터 명령문 String에서 사용할 수 있습니다 switch.

Oracle Docs-Switch의 자세한 내용 switch(널 변수가 포함 된 예 포함)


switch ((i != null) ? i : DEFAULT_VALUE) {
        //...
}

switch(i)내가 경우 NullPointerException이 발생합니다 null가를 언 박싱하려고하기 때문에, Integerint. 따라서 case null불법적 인 것은 어쨌든 결코 도달하지 못했을 것입니다.

switch명령문 앞에 i가 널이 아닌지 확인해야 합니다.


Java 문서는 분명히 다음과 같이 말했습니다.

스위치 레이블로 null을 사용하는 것을 금지하면 실행할 수없는 코드를 작성할 수 없습니다. 스위치식이 박스형 기본 형식 또는 열거 형과 같은 참조 형식 인 경우식이 런타임에서 null로 평가되면 런타임 오류가 발생합니다.

Swithch 문을 실행하기 전에 null을 확인해야합니다.

if (i == null)

스위치 문을 참조하십시오

case null: // will never be executed, therefore disallowed.

주어진:

public enum PersonType {
    COOL_GUY(1),
    JERK(2);

    private final int typeId;
    private PersonType(int typeId) {
        this.typeId = typeId;
    }

    public final int getTypeId() {
        return typeId;
    }

    public static PersonType findByTypeId(int typeId) {
        for (PersonType type : values()) {
            if (type.typeId == typeId) {
                return type;
            }
        }
        return null;
    }
}

For me, this typically aligns with a look-up table in a database (for rarely-updated tables only).

However, when I try to use findByTypeId in a switch statement (from, most likely, user input)...

int userInput = 3;
PersonType personType = PersonType.findByTypeId(userInput);
switch(personType) {
case COOL_GUY:
    // Do things only a cool guy would do.
    break;
case JERK:
    // Push back. Don't enable him.
    break;
default:
    // I don't know or care what to do with this mess.
}

...as others have stated, this results in an NPE @ switch(personType) {. One work-around (i.e., "solution") I started implementing was to add an UNKNOWN(-1) type.

public enum PersonType {
    UNKNOWN(-1),
    COOL_GUY(1),
    JERK(2);
    ...
    public static PersonType findByTypeId(int id) {
        ...
        return UNKNOWN;
    }
}

Now, you don't have to do null-checking where it counts and you can choose to, or not to, handle UNKNOWN types. (NOTE: -1 is an unlikely identifier in a business scenario, but obviously choose something that makes sense for your use-case).


You have to make a

if (i == null) {
   doSomething0();
} else {
   switch (i) {
   }
}

Some libraries attempt to offer alternatives to the builtin java switch statement. Vavr is one of them, they generalize it to pattern matching.

Here is an example from their documentation:

String s = Match(i).of(
    Case($(1), "one"),
    Case($(2), "two"),
    Case($(), "?")
);

You can use any predicate, but they offer many of them out of the box, and $(null) is perfectly legal. I find this a more elegant solution than the alternatives, but this requires java8 and a dependency on the vavr library...


You can also use String.valueOf((Object) nullableString) like

switch (String.valueOf((Object) nullableString)) {
case "someCase"
    //...
    break;
...
case "null": // or default:
    //...
        break;
}

See interesting SO Q/A: Why does String.valueOf(null) throw a NullPointerException


You can't. You can use primitives (int, char, short, byte) and String (Strings in java 7 only) in switch. primitives can't be null.
Check i in separate condition before switch.


switch (String.valueOf(value)){
    case "null":
    default: 
}

Just consider how the SWITCH might work,

  • in case of primitives we know it can fail with NPE for auto-boxing
  • but for String or enum, it might be invoking equals method, which obviously needs a LHS value on which equals is being invoked. So, given no method can be invoked on a null, switch cant handle null.

참고URL : https://stackoverflow.com/questions/10332132/how-to-use-null-in-switch

반응형