2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

这不是真正的“隐藏功能”,也不是很有用,但在某些情况下可能非常有趣: sun.misc.Unsafe类——允许你在Java中实现直接的内存管理(如果你尝试了很多,你甚至可以用它来编写自修改的Java代码):

public class UnsafeUtil {

    public static Unsafe unsafe;
    private static long fieldOffset;
    private static UnsafeUtil instance = new UnsafeUtil();

    private Object obj;

    static {
        try {
            Field f = Unsafe.class.getDeclaredField("theUnsafe");
            f.setAccessible(true);

            unsafe = (Unsafe)f.get(null);
            fieldOffset = unsafe.objectFieldOffset(UnsafeUtil.class.getDeclaredField("obj"));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    };
}

其他回答

对于我面试的大多数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中只是一个关键字?:)

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

class Thing {
  private int x;

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

finally块中的控制权转移会丢弃任何异常。下面的代码不会抛出RuntimeException——它丢失了。

public static void doSomething() {
    try {
      //Normally you would have code that doesn't explicitly appear 
      //to throw exceptions so it would be harder to see the problem.
      throw new RuntimeException();
    } finally {
      return;
    }
  }

从http://jamesjava.blogspot.com/2006/03/dont-return-in-finally-clause.html

他们花了足够长的时间来增加支持,

系统托盘

我知道这是在1.5版中添加的,但是新的enum类型是一个很棒的特性。不必使用旧的“int enum模式”极大地帮助了我的一堆代码。看看JLS 8.9的甜肉汁你的土豆!