在阅读了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).
其他回答
泛型方法的类型参数可以像这样显式指定:
Collections.<String,Integer>emptyMap()
实际上,我喜欢Java的原因是它很少有隐藏的技巧。这是一种非常明显的语言。以至于15年过去了,我能想到的几乎每一个都已经列在这几页纸上了。
也许大多数人都知道Collections.synchronizedList()将同步添加到列表中。除非阅读文档,否则您不可能知道的是,您可以通过同步列表对象本身来安全地迭代该列表的元素。
有些人可能不知道CopyOnWriteArrayList,而Future表示一种抽象多线程结果访问的有趣方法。
您可以通过各种管理、代理和附加api连接到虚拟机(本地或远程),获取关于GC活动、内存使用、文件描述符甚至对象大小的信息。
虽然TimeUnit可能比long更好,但我更喜欢Wicket的Duration类。
几个月前当我第一次发现它时,双括号初始化让我感到惊讶,以前从未听说过它。
作为存储每个线程状态的一种方式,ThreadLocals通常并不广为人知。
由于JDK 1.5 Java已经有了非常好的实现和健壮的并发工具,而不仅仅是锁,它们存在于Java .util.concurrent中,一个特别有趣的例子是Java .util.concurrent.atomic子包,它包含线程安全的原语,实现比较和交换操作,并可以映射到这些操作的实际本机硬件支持版本。
当人们意识到可以使用反射调用私有方法并访问/更改私有字段时,他们有时会有点惊讶……
考虑下面的类:
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]
Javadoc——在正确编写的情况下(不幸的是,一些开发人员并不总是这样),它会为您提供一个清晰、连贯的描述,说明代码应该做什么,而不是它实际做什么。然后可以将其转换为一组不错的可浏览的HTML文档。如果你使用持续集成等方法,它可以定期生成,这样所有开发者都可以看到最新的更新。
推荐文章
- 在Selenium中等待页面加载
- Maven父pom vs模块pom
- 将JSON数据转换为Java对象
- Java的隐藏特性
- 使用Java 8的可选Stream::flatMap
- 使用管道字符("|")分割字符串
- 在IntelliJ中找不到Maven插件
- Java List.add() UnsupportedOperationException
- 连接两个字节数组的简单方法
- 为什么Mockito不模拟静态方法?
- Volatile boolean vs AtomicBoolean
- 在一个类中使用相同的方法实现两个接口。覆盖了哪个接口方法?
- 线程的上下文类装入器和普通类装入器之间的区别
- 如何在Java中正确地比较两个整数?
- 在Java中获取“unixtime”