2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

我喜欢

Javadoc的taglet和doclet使我们能够自定义Javadoc输出。 JDK工具:jstat, jstack等。

其他回答

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

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

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");
                        }
                     });
                 }});
        }});
    }};

静态导入可以“增强”语言,这样你就可以以类型安全的方式做一些漂亮的文字工作:

List<String> ls = List("a", "b", "c");

(也可以做映射,数组,集)。

http://gleichmann.wordpress.com/2008/01/13/building-your-own-literals-in-java-lists-and-arrays/

更进一步说:

List<Map<String, String>> data = List(Map( o("name", "michael"), o("sex", "male")));

The power you can have over the garbage collector and how it manages object collection is very powerful, especially for long-running and time-sensitive applications. It starts with weak, soft, and phantom references in the java.lang.ref package. Take a look at those, especially for building caches (there is a java.util.WeakHashMap already). Now dig a little deeper into the ReferenceQueue and you'll start having even more control. Finally grab the docs on the garbage collector itself and you'll be able to control how often it runs, sizes of different collection areas, and the types of algorithms used (for Java 5 see http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html).

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