When should I use the java 5 method cast of Class?

前端 未结 5 990
抹茶落季
抹茶落季 2020-12-11 02:22

Looking through some code I came across the following code

trTuDocPackTypdBd.update(TrTuDocPackTypeDto.class.cast(packDto));

and I\'d like

5条回答
  •  Happy的楠姐
    2020-12-11 02:28

    I can't find an example where the cast method is possible and the cast syntax not. However, looking at the code, it seems that in case the cast is not possible, the cast method throws a ClassCastException with no type information attached, whereas the cast syntax will give you some hints (as in, "could not cast Snoopy to TyrannosorusRex") :

    /**
     * Casts an object to the class or interface represented
     * by this Class object.
     *
     * @param obj the object to be cast
     * @return 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
     */
    public T cast(Object obj) {
    if (obj != null && !isInstance(obj))
        throw new ClassCastException();
    return (T) obj;
    }
    

提交回复
热议问题