2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

对于我面试的大多数Java开发人员来说,标记为块的职位是非常令人惊讶的。这里有一个例子:

// code goes here

getmeout:{
    for (int i = 0; i < N; ++i) {
        for (int j = i; j < N; ++j) {
            for (int k = j; k < N; ++k) {
                //do something here
                break getmeout;
            }
        }
    }
}

谁说goto在java中只是一个关键字?:)

其他回答

它并不是完全隐藏的,但反射是非常有用和强大的。使用简单的class . forname("…"). newinstance()是很好的,其中类类型是可配置的。编写这种工厂实现很容易。

当你不需要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 1.5开始,Java现在有了更清晰的语法来编写变量函数。不只是传递一个数组,现在您可以执行以下操作

public void foo(String... bars) {
   for (String bar: bars)
      System.out.println(bar);
}

Bars自动转换为指定类型的数组。这不是一个巨大的胜利,但仍然是一场胜利。

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

考虑下面的类:

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]

字符串参数化类工厂。

Class.forName( className ).newInstance();

从部署jar文件中加载资源(属性文件,xml, xslt,图像等)。

this.getClass().getClassLoader().getResourceAsStream( ... ) ;