2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

也许最令人惊讶的隐藏特性是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支持这个类,所以它不能移植。

其他回答

显然,在一些调试版本中,有一个从HotSpot: http://weblogs.java.net/blog/kohsuke/archive/2008/03/deep_dive_into.html转储本机(JIT)程序集代码的选项

不幸的是,我无法通过那篇文章中的链接找到构建,如果有人能找到一个更精确的URL,我很乐意使用它。

您可以定义一个匿名子类,并直接调用它上的方法,即使它没有实现接口。

new Object() {
  void foo(String s) {
    System.out.println(s);
  }
}.foo("Hello");

还没有人提到instanceof的实现方式是不需要检查null的。

而不是:

if( null != aObject && aObject instanceof String )
{
    ...
}

只使用:

if( aObject instanceof String )
{
    ...
}

c风格的printf():)

System.out.printf("%d %f %.4f", 3,Math.E,Math.E);

输出: 3 2.718282 2.7183

二分搜索(以及它的返回值)

int[] q = new int[] { 1,3,4,5};
int position = Arrays.binarySearch(q, 2);

类似于c#,如果在数组中没有找到'2',它会返回一个负值,但如果你对返回值取1的补,你实际上会得到'2'可以插入的位置。

在上面的例子中,position = -2, ~position = 1,这是2应该插入的位置…它还允许您找到数组中“最接近”的匹配项。

我认为它很漂亮……:)

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