2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

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

其他回答

我真的很喜欢从Java 1.6重写的线程API。可调用对象很棒。它们基本上是带有返回值的线程。

当人们意识到可以使用反射调用私有方法并访问/更改私有字段时,他们有时会有点惊讶……

考虑下面的类:

public class Foo {
    private int bar;

    public Foo() {
        setBar(17);
    }

    private void setBar(int bar) {
        this.bar=bar;
    }

    public int getBar() {
        return bar;
    }

    public String toString() {
        return "Foo[bar="+bar+"]";
    }
}

执行这个程序…

import java.lang.reflect.*;

public class AccessibleExample {
    public static void main(String[] args)
        throws NoSuchMethodException,IllegalAccessException, InvocationTargetException, NoSuchFieldException {
        Foo foo=new Foo();
        System.out.println(foo);

        Method method=Foo.class.getDeclaredMethod("setBar", int.class);
        method.setAccessible(true);
        method.invoke(foo, 42);

        System.out.println(foo);
        Field field=Foo.class.getDeclaredField("bar");
        field.setAccessible(true);
        field.set(foo, 23);
        System.out.println(foo);
    }
}

...将产生以下输出:

Foo[bar=17]
Foo[bar=42]
Foo[bar=23]

SwingWorker用于轻松管理后台线程的用户界面回调。

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

系统托盘

值:

new URL("http://www.yahoo.com").equals(new URL("http://209.191.93.52"))

是真的。

(摘自Java Puzzlers)