I'd like to create a type that can be used in the same manner as Boolean
. Specifically, I'd like the test construct to work:
if (mytype) {
System.out.println("true");
}
Clearly the language defines this as a special case in section 5.1.7. And a test application shows it:
public class TypeBoolTest {
public static void main(String args[]) {
Boolean bool = true;
if (bool) {
System.out.println("bool = true");
} else {
System.out.println("bool = false");
}
}
}
/**
Compiled from "TypeBoolTest.java"
public class TypeBoolTest {
public TypeBoolTest();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_1
1: invokestatic #2 // Method java/lang/Boolean.valueOf:(Z)Ljava/lang/Boolean;
4: astore_1
5: aload_1
6: invokevirtual #3 // Method java/lang/Boolean.booleanValue:()Z
9: ifeq 23
12: getstatic #4 // Field java/lang/System.out:Ljava/io/PrintStream;
15: ldc #5 // String bool = true
17: invokevirtual #6 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
20: goto 31
23: getstatic #4 // Field java/lang/System.out:Ljava/io/PrintStream;
26: ldc #7 // String bool = false
28: invokevirtual #6 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
31: return
}
**/
Extending Boolean
won't work because the class is final.
So my question is: is it possible to define a custom type such that Java will recognize that it follows the boolean
boxing and unboxing rules?