2024-04-20 09:00:01

Java的隐藏特性

在阅读了c#的隐藏特性之后,我想知道Java的隐藏特性有哪些?


当前回答

静态导入可以“增强”语言,这样你就可以以类型安全的方式做一些漂亮的文字工作:

List<String> ls = List("a", "b", "c");

(也可以做映射,数组,集)。

http://gleichmann.wordpress.com/2008/01/13/building-your-own-literals-in-java-lists-and-arrays/

更进一步说:

List<Map<String, String>> data = List(Map( o("name", "michael"), o("sex", "male")));

其他回答

真正让我吃惊的是自定义序列化机制。

而这些方法是私有的!!,它们会在对象序列化期间被JVM“神秘地”调用。

private void writeObject(ObjectOutputStream out) throws IOException;
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;

通过这种方式,您可以创建自己的自定义序列化,使其更加“随便”(安全、快速、罕见、简单等)。

如果大量信息必须通过节点传递,这是真正应该考虑的事情。序列化机制可以更改为发送数据的一半。很多时候,瓶颈并不在平台上,而是在通过线路发送的数量上,这可能会为您节省数千个硬件dll。

这是一篇文章。 http://java.sun.com/developer/technicalArticles/Programming/serialization/

当你不需要StringBuilder中包含的同步管理时,使用StringBuilder代替StringBuffer。它将提高应用程序的性能。

Java 7的改进甚至比任何隐藏的Java特性都要好:

菱形语法:Link

不要在实例化时使用那些infinite <>语法:

Map<String, List<String>> anagrams = new HashMap<String, List<String>>();

// Can now be replaced with this:

Map<String, List<String>> anagrams = new HashMap<>();

switch中的字符串:Link

在switch中使用String,而不是old-C int:

String s = "something";
switch(s) {
 case "quux":
    processQuux(s);
    // fall-through

  case "foo":
  case "bar":
    processFooOrBar(s);
    break;

  case "baz":
     processBaz(s);
    // fall-through

  default:
    processDefault(s);
    break;
}

自动资源管理Link

这段旧代码:

static void copy(String src, String dest) throws IOException {
    InputStream in = new FileInputStream(src);
    try {
        OutputStream out = new FileOutputStream(dest);
        try {
            byte[] buf = new byte[8 * 1024];
            int n;
            while ((n = in.read(buf)) >= 0)
                out.write(buf, 0, n);
        } finally {
            out.close();
        }
    } finally {
        in.close();
    }
}

现在可以用更简单的代码代替:

static void copy(String src, String dest) throws IOException {
    try (InputStream in = new FileInputStream(src);
            OutputStream out = new FileOutputStream(dest)) {
        byte[] buf = new byte[8192];
        int n;
        while ((n = in.read(buf)) >= 0)
            out.write(buf, 0, n);
    }
}

实例变量的Final:

对多线程代码非常有用,它使争论实例状态和正确性变得容易得多。在工业环境中还没见过很多,在java类中也没想过。


静态{东西;}:

用于初始化静态成员(我也喜欢用静态方法来做它(因为它有一个名称)。没有思想。

值:

new URL("http://www.yahoo.com").equals(new URL("http://209.191.93.52"))

是真的。

(摘自Java Puzzlers)

不是Java语言的一部分,但是Sun的JDK附带的javap反汇编程序并不广为人知或被广泛使用。