Java:如果 Character 是包装器 class,为什么 "Character newChar = 'c' " 有效?为什么它不需要构造函数?

Java: Why does "Character newChar = 'c' " work if Character is a wrapper class? How come it doesn't need a constructor?

这些对我来说都很好:

示例 1:

Character newCharacter = 'c';

示例 2:

Character newCharacterOther = new Character('c');

但是有什么不同呢?

在第一个示例中,字符 class 如何知道将其值设置为“c”而不需要构造函数?

它在幕后使用工厂方法吗?有人可以向我解释一下编译器是如何知道该做什么的吗?

我提供了 java.lang 中 Character.class 的构造函数的图像。

它甚至说它已被弃用,不应该那样访问它,但我仍然有点困惑。

如所述in the language spec

Assignment contexts allow the use of one of the following:

  • ...
  • a boxing conversion (§5.1.7)
  • ...

参考section 5.1.7:

Specifically, the following nine conversions are called the boxing conversions:

  • ...
  • From type char to type Character
  • ...

At run time, boxing conversion proceeds as follows:

  • ...
  • If p is a value of type char, then boxing conversion converts p into a reference r of class and type Character, such that r.charValue() == p
  • ...

所以,你的行相当于:

Character newCharacter = Character.valueOf('c');

确实,如果您反编译 class,您会发现这正是被调用的内容。


But what are the differences?

new Anything 保证创建 Anything 的新实例(或因异常而失败)。所以,new Character('c') == new Character('c') 总是假的。

另一方面,Character.valueOf('c') == Character.valueOf('c')可能是正确的,因为不需要对return新实例的方法调用。实际上,规范保证您不会在这两个调用中获得新实例。

这允许您重用现有实例,避免不必要的分配,从而节省内存。