Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would I use java.lang.Class.cast [duplicate]

Tags:

I recently stumbled upon a piece of code that went like this:

Object o = .. ;
Foo foo = Foo.class.cast(o);

I was actually not even aware that java.lang.Class had a cast method, so I looked into the docs, and from what I gather this does simply do a cast to the class that the Class object represents. So the code above would be roughly equivalent to

Object o = ..;
Foo foo = (Foo)o;

So I wondered, why I would want to use the cast method instead of simply doing a cast "the old way". Has anyone a good example where the usage of the cast method is beneficial over doing the simple cast?

like image 558
Jan Thomä Avatar asked Oct 26 '11 08:10

Jan Thomä


People also ask

What is the purpose of using Java Lang class class?

This method determines the interfaces implemented by the class or interface represented by this object. This method returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.

Why do we get class cast exception?

Introduction. ClassCastException is a runtime exception raised in Java when we try to improperly cast a class from one type to another. It's thrown to indicate that the code has attempted to cast an object to a related class, but of which it is not an instance.

What is cast method in Java?

The cast() method of java. lang. Class class is used to cast the specified object to the object of this class. The method returns the object after casting in the form of an object. Syntax: public T[] cast(Object obj)

How do you resolve ClassCastException?

// type cast an parent type to its child type. In order to deal with ClassCastException be careful that when you're trying to typecast an object of a class into another class ensure that the new type belongs to one of its parent classes or do not try to typecast a parent object to its child type.


1 Answers

I don't think it's often used exactly as you have shown. Most common use I have seen is where folks using generics are trying to do the equivalent of this:

public static <T extends Number> T castToNumber(Object o) {
    return (T)o;
}

Which doesn't really do anything useful because of type erasure.

Whereas this works, and is type safe (modulo ClassCastExceptions):

public static <T extends Number> T castToNumber(Object o, Class<T> clazz) {
    return clazz.cast(o);
}

EDIT: Couple of examples of use from google guava:

  • MutableClassToInstanceMap
  • Cute use in Throwables#propagateIfInstanceOf, for type safe generic throw spec
like image 131
clstrfsck Avatar answered Oct 27 '22 01:10

clstrfsck