2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

Javadoc——在正确编写的情况下(不幸的是,一些开发人员并不总是这样),它会为您提供一个清晰、连贯的描述,说明代码应该做什么,而不是它实际做什么。然后可以将其转换为一组不错的可浏览的HTML文档。如果你使用持续集成等方法,它可以定期生成,这样所有开发者都可以看到最新的更新。

其他回答

它并不是完全隐藏的,但反射是非常有用和强大的。使用简单的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);
    }
}

"const"是一个关键字,但你不能使用它。

int const = 1;   // "not a statement"
const int i = 1; // "illegal start of expression"

我猜编译器的作者认为将来可能会用到它,他们最好保留它。

因为还没有人说过(我认为)我最喜欢的功能是自动装箱!

public class Example
{
    public static void main(String[] Args)
    {
         int a = 5;
         Integer b = a; // Box!
         System.out.println("A : " + a);
         System.out.println("B : " + b);
    }
}

实际上,我喜欢Java的原因是它很少有隐藏的技巧。这是一种非常明显的语言。以至于15年过去了,我能想到的几乎每一个都已经列在这几页纸上了。

也许大多数人都知道Collections.synchronizedList()将同步添加到列表中。除非阅读文档,否则您不可能知道的是,您可以通过同步列表对象本身来安全地迭代该列表的元素。

有些人可能不知道CopyOnWriteArrayList,而Future表示一种抽象多线程结果访问的有趣方法。

您可以通过各种管理、代理和附加api连接到虚拟机(本地或远程),获取关于GC活动、内存使用、文件描述符甚至对象大小的信息。

虽然TimeUnit可能比long更好,但我更喜欢Wicket的Duration类。