2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

这是我的清单。

我最喜欢的(也是最可怕的)隐藏特性是,您可以从没有声明抛出任何东西的方法中抛出检查异常。

import java.rmi.RemoteException;

class Thrower {
    public static void spit(final Throwable exception) {
        class EvilThrower<T extends Throwable> {
            @SuppressWarnings("unchecked")
            private void sneakyThrow(Throwable exception) throws T {
                throw (T) exception;
            }
        }
        new EvilThrower<RuntimeException>().sneakyThrow(exception);
    }
}

public class ThrowerSample {
    public static void main( String[] args ) {
        Thrower.spit(new RemoteException("go unchecked!"));
    }
}

此外,你可能想知道你可以抛出'null'…

public static void main(String[] args) {
     throw null;
}

猜猜这打印了什么:

Long value = new Long(0);
System.out.println(value.equals(0));

猜猜这返回什么:

public int returnSomething() {
    try {
        throw new RuntimeException("foo!");
    } finally {
        return 0;
    }
}

优秀的开发人员不应该对上述情况感到惊讶。


在Java中,你可以用以下几种有效的方式来声明数组:

String[] strings = new String[] { "foo", "bar" };
// the above is equivalent to the following:
String[] strings = { "foo", "bar" };

所以下面的Java代码是完全有效的:

public class Foo {
    public void doSomething(String[] arg) {}

    public void example() {
        String[] strings = { "foo", "bar" };
        doSomething(strings);
    }
}

是否有任何有效的理由说明下面的代码不应该是有效的?

public class Foo {

    public void doSomething(String[] arg) {}

    public void example() {
        doSomething({ "foo", "bar" });
    }
}

我认为,上述语法可以有效地替代Java 5中引入的可变参数。并且,与之前允许的数组声明更加一致。

其他回答

您可以在枚举类的方法定义中切换(此)。当我发现这个方法真的有效时,我大声喊了一声“什么!”

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

Collections.<String,Integer>emptyMap()

语言级assert关键字。

最终初始化可以推迟。

它确保即使使用复杂的逻辑流也始终设置返回值。很容易错过一个case并意外返回null。它并不是不可能返回null,只是很明显它是故意的:

public Object getElementAt(int index) {
    final Object element;
    if (index == 0) {
         element = "Result 1";
    } else if (index == 1) {
         element = "Result 2";
    } else {
         element = "Result 3";
    }
    return element;
}

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

class Thing {
  private int x;

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