2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

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.util.concurrent,因为它的并发集合和灵活的执行器允许线程池、计划任务和协调任务。DelayQueue是我个人最喜欢的,其中元素在指定的延迟后才可用。

timer和TimerTask可以安全地休息了。

而且,它不是完全隐藏的,而是在与日期和时间相关的其他类不同的包中。timeunit在纳秒、微秒、毫秒和秒之间转换时很有用。

它比通常的someValue * 1000或someValue / 1000读起来要好得多。

您选择的编码中的属性文件如何?过去,当你加载你的属性,你提供了一个InputStream和load()方法解码为ISO-8859-1。你实际上可以用其他编码来存储文件,但你必须在加载后使用像这样令人作呕的黑客来正确解码数据:

String realProp = new String(prop.getBytes("ISO-8859-1"), "UTF-8");

但是,从JDK 1.6开始,有一个load()方法接受Reader而不是InputStream,这意味着您可以从一开始就使用正确的编码(还有一个store()方法接受Writer)。对我来说,这似乎是一件相当大的事情,但它似乎是悄无声息地潜入JDK的。我几周前才偶然发现它,快速搜索谷歌,只发现了一个提及。

类型参数方差的联合:

public class Baz<T extends Foo & Bar> {}

例如,如果你想取一个参数,它既是可比的又是集合的:

public static <A, B extends Collection<A> & Comparable<B>>
boolean foo(B b1, B b2, A a) {
   return (b1.compareTo(b2) == 0) || b1.contains(a) || b2.contains(a);
}

如果两个给定的集合相等,或者其中任何一个包含给定元素,则该方法返回true,否则返回false。需要注意的一点是,您可以对参数b1和b2调用Comparable和Collection方法。

如果你做了很多JavaBean开发,并且使用了属性更改支持,你通常会写很多这样的setter:

public void setFoo(Foo aFoo){
  Foo old = this.foo;
  this.foo = aFoo;
  changeSupport.firePropertyChange("foo", old, aFoo);
}

我最近无意中发现了一篇博客,它提出了一个更简洁的实现,使代码更容易编写:

public void setFoo(Foo aFoo){
  changeSupport.firePropertyChange("foo", this.foo, this.foo = aFoo);
}

它实际上简化了事情,以至于我能够在Eclipse中调整setter模板,从而自动创建方法。

实例变量的Final:

对多线程代码非常有用,它使争论实例状态和正确性变得容易得多。在工业环境中还没见过很多,在java类中也没想过。


静态{东西;}:

用于初始化静态成员(我也喜欢用静态方法来做它(因为它有一个名称)。没有思想。