使用 Sun 专有的 Java 类是一种不好的做法吗?
如果您使用 Sun 专有的 Java 类,编译器会显示警告。我认为使用这些类通常是一个坏主意。我在某处读到过这个。然而,除了警告之外,还有什么根本原因不应该使用它们吗?
The compiler display warnings if you use Sun's proprietary Java classes. I'm of the opinion that it's generally a bad idea to use these classes. I read this somewhere. However, aside from the warnings are there any fundamental reasons why you should not use them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
因为它们是内部 API:它们可能会以未记录或不受支持的方式进行更改,并且它们绑定到特定的 JRE/JDK (Sun在你的情况下),限制了你的程序的可移植性。
尽量避免使用此类 API,始终首选公共记录和指定的类。
Because they are internal APIs: they are subject to change in a undocumented or unsupported way and they are bound to a specific JRE/JDK (Sun in your case), limiting portability of your programs.
Try to avoid uses of such APIs, always prefer a public documented and specified class.
JDK 6 文档 包含一个标题为 关于
sun.*
包的说明。这是 Java 1.2 文档中的文档,因此对sun.*
的引用应视为com.sun.*
其中最重要的一点是:
和
The JDK 6 Documentation includes a link titled Note About
sun.*
Packages. This is a document from the Java 1.2 docs, so references tosun.*
should be treated as if they saidcom.sun.*
The most important points from it are:
and
尝试使用非 Sun JVM 运行您的代码,看看会发生什么...
(您的代码将因 ClassNotFound 异常而失败)
Try running your code with a non-Sun JVM and see what happens...
(Your code will fail with a ClassNotFound exception)
是的,因为没有人保证这些类或 API 与下一个 Java 版本相同,而且我敢打赌,也不能保证这些类在其他供应商的 Java 版本中可用。
因此,您将代码耦合到特殊的 Java 版本,并且至少失去了可移植性。
Yes, because nobody guarantees that these classes or API will be the same with the next Java release and I bet it's not guaranteed that those classes are available in Java versions from other vendors.
So you couple your code to special Java version and loose at least portability.
Sun 的专有 Java 类是其 Java 实现的一部分,而不是 Java API 的一部分,其使用未记录且不受支持。由于它们是内部的,因此可以出于 Sun JVM 团队决定的任何原因随时进行更改。
而且 Sun 的 Java 实现并不是唯一的!您的代码无法移植到 Oracle/BEA 和 IBM 等其他供应商的 JVM。
Sun's proprietary Java classes are part of their Java implementation not part of the Java API their use is undocumented and unsupported. Since they are internal they can be changed at any time for any reason that the team working the Sun JVM decides.
Also Sun's Java implementation is not the only one out there! Your code would not be able portable to JVMs from other vendors like Oracle/BEA and IBM.
以下是 Oracle 的回答:为什么开发人员不应编写调用“sun”的程序' 包
Here is Oracle's answer: Why Developers Should Not Write Programs That Call 'sun' Packages
我最近遇到的一个案例展示了使用这些类时可能遇到的现实问题:我们的代码无法编译,因为它在 sun.* 类上使用的方法根本不存在于 Ubuntu 上的 OpenJDK 中。所以我想当使用这些类时你不能再说“这适用于 Java 5”之类的话,因为它只适用于特定的 Java 实现。
I recently had a case that showed a real-world problem you can hit when you use these classes: we had code that would not compile because a method it was using on a sun.* class simply did not exist in OpenJDK on Ubuntu. So I guess when using these classes you can no longer say things like 'this works with Java 5', because it will only work on a certain Java implementation.