Java 8 中的非字符串(非 int/long)对象的实习
Interning of non String (non int/long) objects in Java 8
我正在阅读来自 Oracle 的文档:https://docs.oracle.com/javase/tutorial/java/annotations/basics.html
并且遇到了这段关于类型注释的代码
Class实例创建表达式:
new @Interned MyObject();
这是否意味着 Java8 或未来版本 is-allowing/will-allow 非 String/long/int 对象的实习?
据我所知还没有这样的计划。这只是一个如何使用注解的例子。我想它可以由像 project Lombok 这样的第三方注释处理器来实现,但我们不太可能在 JDK 中看到这样的功能(至少在不久的将来)。 @Readonly
等其他示例也只是示例,不应将它们添加到 JDK.
请注意,在用户代码中使用 String.intern()
是非常糟糕的。现在它不像 JDK6 那样大的灾难,但它仍然很糟糕。您可以使用 ConcurrentHashMap.putIfAbsent(obj, obj)
.
轻松实现自己的对象池
这个特殊注释似乎源自 Checker Framework—an implementation of pluggable type checking 系统 Java(这本身就是一个非常有趣的概念)。来自 Checker Framework 文档:
If the Interning Checker issues no errors for a given program, then all reference equality tests (i.e., all uses of “==”) are proper; that is, == is not misused where equals() should have been used instead.
Interning is a design pattern in which the same object is used whenever two different objects would be considered equal. Interning is also known as canonicalization or hash-consing, and it is related to the flyweight design pattern. Interning has two benefits: it can save memory, and it can speed up testing for equality by permitting use of ==.
还有一点:
@Interned
indicates a type that includes only interned values (no non-interned values).
Checker Framework 不是 Java 的正式组成部分,但它是由 Oracle 员工开发和推广的,因此在 Java 文档中看到这种稍纵即逝的提及也就不足为奇了。
您可以在 Wikipedia 中阅读有关相关模式的更多信息。
请注意,Java 中有人提议为纯值对象引入额外的语义,名称为 Project Valhalla。如果这些得以实施,对象的互用性将变得更加重要。
我正在阅读来自 Oracle 的文档:https://docs.oracle.com/javase/tutorial/java/annotations/basics.html
并且遇到了这段关于类型注释的代码
Class实例创建表达式:
new @Interned MyObject();
这是否意味着 Java8 或未来版本 is-allowing/will-allow 非 String/long/int 对象的实习?
据我所知还没有这样的计划。这只是一个如何使用注解的例子。我想它可以由像 project Lombok 这样的第三方注释处理器来实现,但我们不太可能在 JDK 中看到这样的功能(至少在不久的将来)。 @Readonly
等其他示例也只是示例,不应将它们添加到 JDK.
请注意,在用户代码中使用 String.intern()
是非常糟糕的。现在它不像 JDK6 那样大的灾难,但它仍然很糟糕。您可以使用 ConcurrentHashMap.putIfAbsent(obj, obj)
.
这个特殊注释似乎源自 Checker Framework—an implementation of pluggable type checking 系统 Java(这本身就是一个非常有趣的概念)。来自 Checker Framework 文档:
If the Interning Checker issues no errors for a given program, then all reference equality tests (i.e., all uses of “==”) are proper; that is, == is not misused where equals() should have been used instead.
Interning is a design pattern in which the same object is used whenever two different objects would be considered equal. Interning is also known as canonicalization or hash-consing, and it is related to the flyweight design pattern. Interning has two benefits: it can save memory, and it can speed up testing for equality by permitting use of ==.
还有一点:
@Interned
indicates a type that includes only interned values (no non-interned values).
Checker Framework 不是 Java 的正式组成部分,但它是由 Oracle 员工开发和推广的,因此在 Java 文档中看到这种稍纵即逝的提及也就不足为奇了。
您可以在 Wikipedia 中阅读有关相关模式的更多信息。
请注意,Java 中有人提议为纯值对象引入额外的语义,名称为 Project Valhalla。如果这些得以实施,对象的互用性将变得更加重要。