Frage

In Java, the Boolean wrapper class contains a method called booleanValue() that returns the boolean primitive type of the value of the Boolean Object.

The thing that interests me about this is that the Java compiler recognizes this booleanValue() method and automatically adds it whenever a Boolean is used when a boolean is needed; for example, if you write an if statement like if (something) where something is a Boolean Object, then compile the code and decompile the result, you'll see that the code now reads if (something.booleanValue()). It's almost like the compiler recognizes that the fact that the Boolean Object class has the booleanValue() method and automatically puts it in the same way that it can add toString() to the end of any Object added in a String addition expression.

So, my question is how can I use this in a custom Object class? Is there a way to make an Object class with a booleanValue() or intValue() method that is recognized by the compiler in the same way as with wrapper classes like Boolean and Integer?

I have found that the Boolean Object class only implements two interfaces: Comparable<Boolean> and Serializable. Since neither of these include a booleanValue() method, I don't understand how the Java compiler recognizes the booleanValue() method in the Boolean Object class and uses it the way it does. I tried simply making a booleanValue() method in my custom Object class and attempted to use the Object like a boolean, but to no avail.

Any ideas?

War es hilfreich?

Lösung

The key sentence in your question is

that is recognized by the compiler

Unless you write your own compiler, you cannot make the compiler do anything. The fact that booleanValue() works is because the Java Language Specification requires it.

If r is a reference of type Boolean, then unboxing conversion converts r into r.booleanValue()

The method booleanValue is declared in java.lang.Boolean.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top