3

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?

James Sumners
  • 14,485
  • 10
  • 59
  • 77

1 Answers1

12

No, it is not possible to define your own types that can be auto(un)boxed by Java.

Auto(un)boxing only works with a specific set of standard types (the wrapper types: Boolean, Integer, Long etc.) and there is no way to extend this with user-defined types.

The list of types that can be autoboxed and -unboxed is defined in the Java Language Specification sections 5.1.7 and 5.1.8.

Jesper
  • 202,709
  • 46
  • 318
  • 350