像Boolean这样的自定义Java类型? [英] Custom Java type that acts like Boolean?

查看:135
本文介绍了像Boolean这样的自定义Java类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个可以与 Boolean 相同的方式使用的类型。具体来说,我希望测试结构有效:

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");
}

显然语言将此定义为第5.1.7节。测试应用程序显示它:

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.

所以我的问题是:是否可以定义一个自定义类型,以便Java识别它遵循布尔装箱和拆箱规则?

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?

推荐答案

不,无法定义您自己的类型,可以由Java自动(un)装箱。

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.

可以自动装箱和-unboxed的类型列表在Java语言规范部分中定义< a href =h ttps://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.7\"rel =noreferrer> 5.1.7 和 5.1.8

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.

这篇关于像Boolean这样的自定义Java类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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