站内搜索: 请输入搜索关键词

当前页面: 开发资料首页J2SE 专题J2SE 5.0 的角落

J2SE 5.0 的角落

摘要: J2SE 5.0 的角落

1,dynamic cast

类似C++的dynamic_cast操作符,C#的as操作符,Java 5.0提供了安全的dynamic cast功能,不同的是它以类库的形式提供的,并且类型不匹配时是要抛异常的,大大降低了可用性:

Class.cast

public T cast(Object obj)
Casts an object to the class or interface represented by this Class object.  
Parameters:
obj - the object to be cast
Returns:
the object after casting, or null if obj is null
Throws:
ClassCastException - if the object is not null and is not assignable to the type T.
Since:
1.5

2,返回值协变

interface SomeInterface{
Object get();
}

class CovariantImpl implements SomeInterface{
public String get(){
return "covariant";
}
}

public class TestUntitled2 extends TestCase {
public void testCovariant() {
SomeInterface obj = new CovariantImpl();
Assert.assertEquals("covariant", obj.get());
}
}

3,类型安全的代理

类似只读代理Collections.unmodifiableXXX(), 同步代理Collections.synchronizedXXX(), J2SE 5.0提供了类型安全的代理:Collections.checkedXXX()

4,Arrays.deepEquals()

不愧是放在java.util包里的

5,皇帝的“generic”新衣

6,基于返回值的类型推导

不知算不算“擦除法”带来的特性 

例一、Collections.emptyXXX()

emptyList

public static final  List emptyList()
Returns the empty list (immutable). This list is serializable.

This example illustrates the type-safe way to obtain an empty list:

     List s = Collections.emptyList(); 
Implementation note: Implementations of this method need not create a separate List object for each call. Using this method is likely to have comparable cost to using the like-named field. (Unlike this method, the field does not provide type safety.)

 

Since:
1.5
See Also:
EMPTY_LIST

例二、一步一次推导

但如果其返回值用于另外一个函数的泛型参数,则必须用临时变量过渡一下,可能是因为不能同时进行两步推导

public class ConditionParser {
private ConditionParser(){
}

public static Condition deserialize(String condition){
....
}
}

List< Condition > conditions = new ArrayList< Condition >();
Condition safe = ConditionParser.deserialize(condition.ToXML());
conditions.add(safe);//ok
 

List< Condition > conditions = new ArrayList< Condition >();
conditions.add(ConditionParser.deserialize(condition.ToXML()));//error

7,类型安全的Varargs

其实是数组的简写形式,因此是类型安全的,带来方便的同时,尚未发现有什么副作用

8,serialVersionUID

到今天了还用实现来暴露意图,殆也,用Annotation来实现也比现在顺眼一点,眼睁睁的看着它混在业务数据对象中

9,面向对象的enum

区别于C++中的enum,J2SE 5.0中的enum是符合“UML有限子类”情形的面向对象的实现(尽管看起来像“有限实例”):可以实现接口,可以有构造函数,可以有方法,成员,除了不能继承和被继承,构造函数必须私有,其它的和普通Java类差不多

(to be continue...)
(The Java Programming Language Notes )




↑返回目录
前一篇: 谈谈J2SE中的序列化
后一篇: Five Reasons to Move to the J2SE 5 Platform