Is autoboxing possible for the classes I create?

前端 未结 4 795
生来不讨喜
生来不讨喜 2020-11-27 19:45

Is there any way to use autoboxing for the classes I create? For example, I have this subclass of Number.

public class UnsignedInteger extends N         


        
4条回答
  •  攒了一身酷
    2020-11-27 20:09

    If you use Groovy, you can set the boolean behavior by implementing the asBoolean method: http://groovy-lang.org/semantics.html#_customizing_the_truth_with_asboolean_methods

    Example:

    class Color {
        String name
    
        boolean asBoolean(){
            name == 'green' ? true : false
        }
    }
    
    assert new Color(name: 'green')
    assert !new Color(name: 'red')
    

    I know this is not plain Java but compiles to bytecode and runs on the JVM.

提交回复
热议问题