2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

几个月前当我第一次发现它时,双括号初始化让我感到惊讶,以前从未听说过它。

作为存储每个线程状态的一种方式,ThreadLocals通常并不广为人知。

由于JDK 1.5 Java已经有了非常好的实现和健壮的并发工具,而不仅仅是锁,它们存在于Java .util.concurrent中,一个特别有趣的例子是Java .util.concurrent.atomic子包,它包含线程安全的原语,实现比较和交换操作,并可以映射到这些操作的实际本机硬件支持版本。

其他回答

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

我喜欢方法的静态导入。

例如,创建以下util类:

package package.name;

public class util {

     private static void doStuff1(){
        //the end
     }

     private static String doStuff2(){
        return "the end";
     }

}

然后像这样使用它。

import static package.name.util.*;

public class main{

     public static void main(String[] args){
          doStuff1(); // wee no more typing util.doStuff1()
          System.out.print(doStuff2()); // or util.doStuff2()
     }

}

静态导入适用于任何类,甚至数学…

import static java.lang.Math.*;
import static java.lang.System.out;
public class HelloWorld {
    public static void main(String[] args) {
        out.println("Hello World!");
        out.println("Considering a circle with a diameter of 5 cm, it has:");
        out.println("A circumference of " + (PI * 5) + "cm");
        out.println("And an area of " + (PI * pow(5,2)) + "sq. cm");
    }
}

一些控制流的技巧,最后围绕一个return语句:

int getCount() { 
  try { return 1; }
  finally { System.out.println("Bye!"); }
}

确定赋值规则将检查最终变量总是通过简单的控制流分析进行赋值:

final int foo;
if(...)
  foo = 1;
else
  throw new Exception();
foo+1;

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

Self-bound泛型:

class SelfBounded<T extends SelfBounded<T>> {
}

http://www.artima.com/weblogs/viewpost.jsp?thread=136394