在阅读了c#的隐藏特性之后,我想知道Java的隐藏特性有哪些?
当前回答
语言级assert关键字。
其他回答
我真的很喜欢从Java 1.6重写的线程API。可调用对象很棒。它们基本上是带有返回值的线程。
动态代理(在1.3中添加)允许您在运行时定义符合接口的新类型。它派上用场的次数多得惊人。
如果你做了很多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模板,从而自动创建方法。
在枚举中允许使用方法和构造函数让我感到惊讶。例如:
enum Cats {
FELIX(2), SHEEBA(3), RUFUS(7);
private int mAge;
Cats(int age) {
mAge = age;
}
public int getAge() {
return mAge;
}
}
你甚至可以有一个“常量特定类主体”,它允许特定的枚举值覆盖方法。
更多文档请点击这里。
使用此关键字从内部类访问包含类的字段/方法。在下面的例子中,我们希望使用匿名内部类的容器类的sortAscending字段。使用ContainerClass.this.sortAscending代替this。sortAscending就是这样。
import java.util.Comparator;
public class ContainerClass {
boolean sortAscending;
public Comparator createComparator(final boolean sortAscending){
Comparator comparator = new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
if (sortAscending || ContainerClass.this.sortAscending) {
return o1 - o2;
} else {
return o2 - o1;
}
}
};
return comparator;
}
}
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap