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支持这个类,所以它不能移植。

其他回答

大多数人不知道他们可以克隆一个数组。

int[] arr = {1, 2, 3};
int[] arr2 = arr.clone();

不那么隐蔽,但很有趣。

你可以有一个没有main方法的"Hello, world"(它会抛出NoSuchMethodError思想)

最初由RusselW在最奇怪的语言功能上发布

public class WithoutMain {
    static {
        System.out.println("Look ma, no main!!");
        System.exit(0);
    }
}

$ java WithoutMain
Look ma, no main!!

同一个类的实例可以访问其他实例的私有成员:

class Thing {
  private int x;

  public int addThings(Thing t2) {
    return this.x + t2.x;  // Can access t2's private value!
  }
}

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

而不是:

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

只使用:

if( aObject instanceof String )
{
    ...
}

对于我面试的大多数Java开发人员来说,标记为块的职位是非常令人惊讶的。这里有一个例子:

// code goes here

getmeout:{
    for (int i = 0; i < N; ++i) {
        for (int j = i; j < N; ++j) {
            for (int k = j; k < N; ++k) {
                //do something here
                break getmeout;
            }
        }
    }
}

谁说goto在java中只是一个关键字?:)