2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

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

Collections.<String,Integer>emptyMap()

其他回答

"const"是一个关键字,但你不能使用它。

int const = 1;   // "not a statement"
const int i = 1; // "illegal start of expression"

我猜编译器的作者认为将来可能会用到它,他们最好保留它。

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

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

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

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

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

也许最令人惊讶的隐藏特性是sun.misc.Unsafe类。

http://www.docjar.com/html/api/ClassLib/Common/sun/misc/Unsafe.java.html

你可以;

Create an object without calling a constructor. Throw any exception even Exception without worrying about throws clauses on methods. (There are other way to do this I know) Get/set randomly accessed fields in an object without using reflection. allocate/free/copy/resize a block of memory which can be long (64-bit) in size. Obtain the location of fields in an object or static fields in a class. independently lock and unlock an object lock. (like synchronize without a block) define a class from provided byte codes. Rather than the classloader determining what the byte code should be. (You can do this with reflection as well)

BTW:不正确地使用这个类会杀死JVM。我不知道哪个jvm支持这个类,所以它不能移植。

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

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")));