2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

没读到过

Integer a = 1;
Integer b = 1;
Integer c = new Integer(1);
Integer d = new Integer(1);

Integer e = 128;
Integer f = 128;

assertTrue (a == b);   // again: this is true!
assertFalse(e == f); // again: this is false!
assertFalse(c == d);   // again: this is false!

通过搜索java的整数池(内部“缓存”从-128到127用于自动装箱)或查看integer . valueof来了解更多信息

其他回答

Java 6以来的类路径通配符。

java -classpath ./lib/* so.Main

而不是

java -classpath ./lib/log4j.jar:./lib/commons-codec.jar:./lib/commons-httpclient.jar:./lib/commons-collections.jar:./lib/myApp.jar so.Main

参见http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html

当我第一次注意到三元运算符等于一个简单的if-then-else语句时,我很惊讶:

minVal = (a < b) ? a : b;

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

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

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

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

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

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

考虑下面的类:

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]

值:

new URL("http://www.yahoo.com").equals(new URL("http://209.191.93.52"))

是真的。

(摘自Java Puzzlers)