2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

我个人很晚才发现java.lang.Void——结合泛型提高了代码的可读性,例如Callable<Void>

其他回答

JDK 1.6_07+包含一个名为VisualVM (bin/jvisualvm.exe)的应用程序,它是许多工具之上的一个漂亮的GUI。它似乎比JConsole更全面。

这并不是一个真正的隐藏功能,但当我看到这个编译好的时候,它确实给了我一个很大的惊喜:

public int aMethod(){
    http://www.google.com
    return 1;
}

它被编译的原因是编译器将http://www.google.com行“http:”部分视为标签,而该行的其余部分是注释。

所以,如果你想写一些奇怪的代码(或模糊的代码),只要在那里放很多http地址。: -)

当你不需要StringBuilder中包含的同步管理时,使用StringBuilder代替StringBuffer。它将提高应用程序的性能。

Java 7的改进甚至比任何隐藏的Java特性都要好:

菱形语法:Link

不要在实例化时使用那些infinite <>语法:

Map<String, List<String>> anagrams = new HashMap<String, List<String>>();

// Can now be replaced with this:

Map<String, List<String>> anagrams = new HashMap<>();

switch中的字符串:Link

在switch中使用String,而不是old-C int:

String s = "something";
switch(s) {
 case "quux":
    processQuux(s);
    // fall-through

  case "foo":
  case "bar":
    processFooOrBar(s);
    break;

  case "baz":
     processBaz(s);
    // fall-through

  default:
    processDefault(s);
    break;
}

自动资源管理Link

这段旧代码:

static void copy(String src, String dest) throws IOException {
    InputStream in = new FileInputStream(src);
    try {
        OutputStream out = new FileOutputStream(dest);
        try {
            byte[] buf = new byte[8 * 1024];
            int n;
            while ((n = in.read(buf)) >= 0)
                out.write(buf, 0, n);
        } finally {
            out.close();
        }
    } finally {
        in.close();
    }
}

现在可以用更简单的代码代替:

static void copy(String src, String dest) throws IOException {
    try (InputStream in = new FileInputStream(src);
            OutputStream out = new FileOutputStream(dest)) {
        byte[] buf = new byte[8192];
        int n;
        while ((n = in.read(buf)) >= 0)
            out.write(buf, 0, n);
    }
}

如果不使用默认初始化式,Java处理在变量定义上做了一个巧妙的技巧。

{
   int x;

   if(whatever)
      x=1;

   if(x == 1)
      ...
}

这将在编译时给您一个错误,即您有一个X未正确定义的路径。这帮助了我几次,我已经开始考虑默认的初始化,像这样:

int x=0;
String s=null;

这是一个不好的模式,因为它阻碍了这种有用的检查。

也就是说,有时很难解决这个问题——当它作为默认值有意义时,我不得不回去编辑=null,但我再也没有在第一次传递时把它放在里面了。

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

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