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

前端 未结 5 989
抹茶落季
抹茶落季 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条回答
  •  轮回少年
    2020-12-11 02:48

    These statements are not identical. The cast method is a normal method invocation (invokevirtual JVM instruction) while the other is a language construct (checkcast instruction). In the case you show above, you should use the second form: (TrTuDocPackTypeDto) packDto

    The cast method is used in reflective programming with generics, when you have a Class instance for some variable type. You could use it like this:

    public  Set find(Class clz, Filter criteria) {
      List raw = session.find(clz, criteria); /* A legacy, un-generic API. */
      Set safe = new HashSet();
      for (Object o : raw) 
        safe.add(clz.cast(o));
      return safe;
    }
    

    This gives you a safe way to avoid the incorrect alternative of simply casting a raw type to a generic type:

    /* DO NOT DO THIS! */
    List raw = new ArrayList();
    ...
    return (List) raw;
    

    The compiler will warn you, Unchecked cast from List to List, meaning that in the ellipsis, someone could have added a Gadget to the raw list, which will eventually cause a ClassCastException when the caller iterates over the returned list of (supposed) Widget instances.

提交回复
热议问题