2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

最终初始化可以推迟。

它确保即使使用复杂的逻辑流也始终设置返回值。很容易错过一个case并意外返回null。它并不是不可能返回null,只是很明显它是故意的:

public Object getElementAt(int index) {
    final Object element;
    if (index == 0) {
         element = "Result 1";
    } else if (index == 1) {
         element = "Result 2";
    } else {
         element = "Result 3";
    }
    return element;
}

其他回答

我今天才(重新)了解到$是Java中方法或变量的合法名称。与静态导入相结合,可以生成一些可读性稍强的代码,这取决于你对可读的看法:

http://garbagecollected.org/2008/04/06/dollarmaps/

The power you can have over the garbage collector and how it manages object collection is very powerful, especially for long-running and time-sensitive applications. It starts with weak, soft, and phantom references in the java.lang.ref package. Take a look at those, especially for building caches (there is a java.util.WeakHashMap already). Now dig a little deeper into the ReferenceQueue and you'll start having even more control. Finally grab the docs on the garbage collector itself and you'll be able to control how often it runs, sizes of different collection areas, and the types of algorithms used (for Java 5 see http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html).

我知道Java 6包括脚本支持,但我最近才发现jrunscript, 它可以交互式地解释和运行JavaScript(以及其他脚本语言,如Groovy),有点像Ruby中的Python shell或irb

语言级assert关键字。

泛型方法的类型参数可以像这样显式指定:

Collections.<String,Integer>emptyMap()