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

其他回答

这是我的清单。

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

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中引入的可变参数。并且,与之前允许的数组声明更加一致。

不那么隐蔽,但很有趣。

你可以有一个没有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!!

在1.5中增加了for-each循环结构。我<3它。

// For each Object, instantiated as foo, in myCollection
for(Object foo: myCollection) {
  System.out.println(foo.toString());
}

并且可以在嵌套实例中使用:

for (Suit suit : suits)
  for (Rank rank : ranks)
    sortedDeck.add(new Card(suit, rank));

for-each结构也适用于数组,它隐藏了索引变量而不是迭代器。下面的方法返回int数组中所有值的和:

// Returns the sum of the elements of a
int sum(int[] a) {
  int result = 0;
  for (int i : a)
    result += i;
  return result;
}

链接到Sun文档

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

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

一些人已经发布了关于实例初始化器的文章,下面是它的一个很好的用法:

Map map = new HashMap() {{
    put("a key", "a value");
    put("another key", "another value");
}};

是初始化映射的快速方法,如果你只是做一些快速简单的事情。

或者用它来创建一个快速摆动框架原型:

JFrame frame = new JFrame();

JPanel panel = new JPanel(); 

panel.add( new JLabel("Hey there"){{ 
    setBackground(Color.black);
    setForeground( Color.white);
}});

panel.add( new JButton("Ok"){{
    addActionListener( new ActionListener(){
        public void actionPerformed( ActionEvent ae ){
            System.out.println("Button pushed");
        }
     });
 }});


 frame.add( panel );

当然,它也可能被滥用:

    JFrame frame = new JFrame(){{
         add( new JPanel(){{
               add( new JLabel("Hey there"){{ 
                    setBackground(Color.black);
                    setForeground( Color.white);
                }});

                add( new JButton("Ok"){{
                    addActionListener( new ActionListener(){
                        public void actionPerformed( ActionEvent ae ){
                            System.out.println("Button pushed");
                        }
                     });
                 }});
        }});
    }};