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

This question already has answers here:
When should I use the java 5 method cast of Class?
(5 answers)
Java Class.cast() vs. cast operator
(8 answers)
Closed 4 years ago.
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?

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

In Java there is often more than one way to skin a cat. Such functionality may be useful in cases where you have framework code. Imagine a method which accepts a Class object instance and an Object instance and returns the Object case as the class:
public static void doSomething(Class<? extends SomeBaseClass> whatToCastAs,Object o)
{
SomeBaseClass castObj = whatToCastAs.cast(o);
castObj.doSomething();
}
In general, use the simpler casting, unless it does not suffice.

In some cases, you only know the type to cast an object to during runtime, and that's when you have to use the cast method.

There is absolutely no reason to write Foo.class.cast(o), it is equivalent to (Foo)o.
In general, if X is a reifiable type, and Class<X> clazz, then clazz.cast(o) is same as (X)o.
If all types are reifiable, method Class.cast() is therefore redundant and useless.
Unfortunately, due to erasure in current version of Java, not all types are reifiable. For example, type variables are not reifiable.
If T is a type variable, cast (T)o is unchecked, because at runtime, the exact type of T is unknown to JVM, JVM cannot test if o is really type T. The cast may be allowed erroneously, which may trigger problems later.
It is not a huge problem; usually when the programmer does (T)o, he has already reasoned that the cast is safe, and won't cause any problem at runtime. The cast is checked by app logic.
Suppose a Class<T> clazz is available at the point of cast, then we do know what T is at runtime; we can add extra runtime check to make sure o is indeed a T.
check clazz.isInstance(o);
(T)o;
And this is essentially what Class.cast() does.
We would never expect the cast to fail in any case, therefore in a correctly implemented app, check clazz.isInstance(o) must always succeed anway, therefore clazz.cast(o) is equivalent to (T)o - once again, under the assumption that the code is correct.
If one can prove that the code is correct and the cast is safe, one could prefer (T)o to clazz.cast(o) for performance reason. In the example of MutableClassToInstanceMap raised in another answer, we can see obviously that the cast is safe, therefore simple (T)o would have sufficed.

class.cast is designed for generics type.
When you construct a class with generic parameter T, you can pass in a
Class. You can then do the cast with both static and dynamic
checking, which (T) does not give you. It also doesn't produce unchecked
warnings, because it is checked (at that point).

The common sample for that is when you retrieve from persistent layer a collection of entity referenced with a Class Object and some conditions. The returned collection could contain unchecked objects, so if you just cast it as pointed G_H, you will throw the Cast Exception at this point, and not when the values are accessed.
One example for this is when you retrieve a collection from a DAO that returns an unchecked collection and on your service you iterate over it, this situation can lead to a ClassCastException.
One way to solve it, as you have the wanted class and the unchecked collection is iterate over it and cast it inside the DAO transforming the collection in a checked collection and afterwards return it.

Because you might have something this:
Number fooMethod(Class<? extends Number> clazz) {
return clazz.cast(var);
}

A "cast" in Java, e.g. (Number)var, where the thing inside the parentheses is a reference type, really consists of two parts:
Compile time: the result of the cast expression has the type of the type you cast to
Run time: it inserts a check operation, which basically says, if the object is not an instance of that class, then throw a ClassCast Exception (if the thing you're casting to is a type variable, then the class it checks would be the lower bound of the type variable)
To use the syntax, you need to know the class at the time you write the code. Suppose you don't know at compile-time what class you want to cast to; you only know it at runtime.
Now you would ask, then what is the point of casting? Isn't the point of casting to turn the expression into the desired type at compile time? So if you don't know the type at compile time, then there is no benefit at compile-time, right? True, but that is just the first item above. You're forgetting the runtime component of a cast (second item above): it checks the object against the class.
Therefore, the purpose of a runtime cast (i.e. Class.cast()) is to check that the object is an instance of the class, and if not, throw an exception. It is roughly equivalent to this but shorter:
if (!clazz.isInstance(var))
throw new ClassCastException();
Some people have mentioned that Class.cast() also has a nice return type that is based on the type parameter of the class passed in, but that is just a compile-time feature that is provided by a compile-time cast anyway. So for that purpose there is no point in using Class.cast().

Related

Java Generics with class object as generic type

I want to create a Java Object for a class that is defined using generics.
Specifically, i want to create a List of Objects of class that is determined at runtime.
I would want something like
Class clazz = Class.forName("MyClass");
List<clazz> myList = new ArrayList<>(); // This isn't allowed
Defining an array of object would allow me to store a list of MyClass type objects, but that would lead to casting the objects every-time the object is fetched from the list, i would like to avoid such a scenario.
Is there a way to achieve something like the above code using java.
Well, since you know that class, you could (with a warning) cast the List itself; but you would still need to know the class name and some checks for that, like for example:
if(clazz.getName().equals("java.lang.String")) {
// warning here
yourList = (List<String>) yourList;
}
As I understand your question, you want to know if is possible for the compiler to know the runtime type while it is limited to the compile type.
You can't. And your hypothesis is also wrong:
Defining an array of object would allow me to store a list of MyClass
type objects, but that would lead to casting the objects every-time
the object is fetched from the list, i would like to avoid such a
scenario.
In Java, generics does not remove the cast: it is still there in the form of type erasure and (hidden) cast. When you do List<String>, you merely ask the compiler to hide the cast in operation such as T get(int): there will be a cast to String.
If you want to use the compile time information, than that would mean you already have/know the type MyClass available at compile time and you would not use Class::forName but MyClass.class which would return a Class<MyClass>.
What you can do is either:
Use an interface if you have a common ground for theses classes (like JDBC Driver).
Cast the raw list into a known type, for example using Class::isAssignableFrom.
No, you can't. Generics in Java is just a compile-time type checking mechanism. If you don't know the type until runtime, then, obviously, it cannot be used for compile-time type checking. The compiler can't determine at compile time what types to allow you to put into or get out of a List<clazz>, so it's no more meaningful than just a raw type List.
There is a little trick that can be used to work with a specific unknown type: Declare a type parameter that is only used for the unknown type:
public <T> void worksWithSomeUnknownClass() throws ReflectiveOperationException {
#SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) Class.forName("MyClass");
T obj = clazz.getConstructor().newInstance();
List<T> myList = new ArrayList<>();
myList.add(obj);
}
This solution is very limited though. It makes sure that you don't mix it up with other unknown types or Object, but you can not really do anything with T. And you have to declare a type parameter on every method that uses it.

Generic Erasure concept

Could you please help me to understand the generic concept here.
// Can't create an instance of T.
class Gen<T> {
T ob;
Gen() {
ob = new T(); // Illegal!!!
}
public static void main() {
Gen<Integer> genobj = new Gen<Integer>(); //Error
}
}
When your Java code is compiled, all generic type
information is removed (erased). This means replacing type parameters with their bound
type, which is Object if no explicit bound is specified, and then applying the appropriate
casts (as determined by the type arguments) to maintain type compatibility with the types
specified by the type arguments. The compiler also enforces this type compatibility.
My question:-Why java complier is throwing error here ?
Bevause after complitaion .
Thanks
There are a few ways that may work out here:
From a logical POV:
It's not even guaranteed that whatever template-parameter T you use has a default-constructor. Which obviously offers the problem of how to handle the absence of a default-constructor. Possible solutions would be to produce a runtime-error, compile-time error or disallow any T that doesn't provide a default-constructor. The latter would obviously break the template-definition, which allows any T. And the runtime-error would complicate things quite a bit and yield the same problem as mentioned above. Remains preventing this behavior in the first place and throwing a compile-time error.
From a internal view:
Let's assume we could use the provided code. Then how would it work? Due to erasure, new T() would produce an Object. But what if T is Integer? Well, we're screwed. An Object is not an Integer, so we'll get a plain class-cast exception.
So in summary: allowing the above to compile wouldn't work from a practical POV and in addition break the current definition of generics in java.

Java Object return type vs. Generic Methods

I saw several questions about generic return type, but none answers my question.
If there is no bound for any of the arguments, such as the following method in JayWay :
public static <T> T read(String json, String jsonPath, Filter... filters) {
return new JsonReader().parse(json).read(jsonPath, filters);
}
What is the point of using this as generic ?
I told the guys from my team that this method should be used as :
JsonPath.<Boolean>read(currentRule, "$.logged")
instead of:
(boolean) JsonPath.read(currentRule, "$.logged")
But I really can't tell the difference...
Generics work by the compiler inserting invisible casts into your code.
For example, before generics were added to the language you'd have to do this.
List list = new ArrayList();
list.add("Foo");
list.add("Bar");
String str0 = (String) list.get(0);
String str1 = (String) list.get(1);
This was very annoying. Because get() returned Object, you had to cast every single time you wanted to get a String from the List.
Nowadays, List is generic, and get() returns T, so you can just do this.
List<String> list = new ArrayList<>();
list.add("Foo");
list.add("Bar");
String str0 = list.get(0);
String str1 = list.get(1);
What is happening here is that the compiler turns the new version into the old version by adding the casts for you, but they're still there.
However, the entire point of generics is that these compiler generated casts are guaranteed to be safe - i.e. they can't possibly throw a ClassCastException at runtime.
In my opinion, if you use generics to hide casts that are not guaranteed to be safe, just because they're annoying, it is an abuse of the feature.
Whether it's a generic method and you do
Boolean a = JsonPath.<Boolean>read(currentRule, "$.logged");
or it returns Object and you do
Boolean a = (Boolean) JsonPath.read(currentRule, "$.logged");
both versions could throw a ClassCastException at runtime, so I think it's better if you are forced to cast so that at least you are aware that you're doing something that could fail.
I consider it bad practice for the return type of a generic method to involve the type parameter T if the method parameters do not, unless the returned object cannot be used in a way that compromises type safety. For example,
public static <T> List<T> emptyList()
in Collections is ok (the list is empty so it can't contain an element of the wrong type).
In your case, I think the read method should not be generic and should just return Object.
The main reason that I would stay away from
JsonPath.<Boolean>read(currentRule, "$.logged")
is that it is internally performing an unchecked cast, and hiding this fact. For instance, you could invoke this method at the same place:
JsonPath.<String>read(currentRule, "$.logged")
and there is no way that you'd know there might be a problem there until it actually happens at runtime - it still compiles, and you don't even get a warning.
There is no getting away from the unchecked cast - I'd just rather have it right there in front of me in the code, so I know there is a potential danger; this allows me to take reasonable steps to mitigate the issue.
#SuppressWarnings("unchecked") // I know something might go wrong here!
boolean value = (boolean) JsonPath.read(currentRule, "$.logged")
Having a type-parameter that has never been set (when calling JsonPath.read(currentRule, "$.logged")), actually makes the compiler completely ignore all the generic information within the method and replace all the type-parameter with:
Object, if the type-parameter doesn't have an upper-bound. (like in your case)
U, if the type-parameter is bounded like <T extends U>. For example, if you have a <T extends Number> as a type-parameter and ignore it by calling JsonPath.read(...), then the compiler will replace the type-parameter with Number.
In the case with the cast ((boolean) JsonPath.read(...)), the type-parameter is replaced with Object. Then, this type is unsafely transformated to boolean, by first returning a Boolean (probably), and then auto-unboxing this wrapper to boolean. This is not safe, at all. Actually, every cast is not safe - pretty much you tell the compiler: "I know what this type will be at Runtime, so please believe me, and let me cast it to something else that's compatible with it.". Your humble servant, the compiler, allows that, but that's not safe, if you're wrong. :)
There's another thing with your method, also. The type-parameter is never used within the method body or parameters - this makes it pretty redundant. Since by doing a cast to boolean you insist that you know the return type of new JsonReader().parse(json).read(jsonPath, filters);, then you should just make the return type boolean (or Boolean):
public static Boolean read(String json, String jsonPath, Filter... filters) {
return new JsonReader().parse(json).read(jsonPath, filters);
}
There is nothing functionally different between the two. The byte-code will probably be identical.
The core difference is that one uses a cast while the other uses generics.
I would generally try to avoid casting if there is any alternative mechanism and as the generic form is a perfectly effective alternative I would go for that.
// The right way.
JsonPath.<Boolean>read(currentRule, "$.logged");

Java reflection get runtime type when using generics

I am wondering how can I get the runtime type which is written by the programmer when using generics. For example if I have class Main<T extends List<String>> and the programmer write something like
Main<ArrayList<String>> main = new Main<>();
how can I understand using reflection which class extending List<String> is used?
I'm just curious how can I achieve that. With
main.getClass().getTypeParameters()[0].getBounds[]
I only can understand the bounding class (not the runtime class).
As the comments above point out, due to type erasure you can't do this. But in the comments, the follow up question was:
I know that the generics are removed after compilation, but I am wondering how then ClassCastException is thrown runtime ? Sorry, if this is a stupid question, but how it knows to throws this exception if there isn't any information about classes.
The answer is that, although the type parameter is erased from the type, it still remains in the bytecode.
Essentially, the compiler transforms this:
List<String> list = new ArrayList<>();
list.add("foo");
String value = list.get(0);
into this:
List list = new ArrayList();
list.add("foo");
String value = (String) list.get(0); // note the cast!
This means that the type String is no longer associated with the type ArrayList in the bytecode, but it still appears (in the form of a class cast instruction). If at runtime the type is different you'll get a ClassCastException.
This also explains why you can get away with things like this:
// The next line should raise a warning about raw types
// if compiled with Java 1.5 or newer
List rawList = new ArrayList();
// Since this is a raw List, it can hold any object.
// Let's stick a number in there.
rawList.add(new Integer(42));
// This is an unchecked conversion. Not always wrong, but always risky.
List<String> stringList = rawList;
// You'd think this would be an error. But it isn't!
Object value = stringList.get(0);
And indeed if you try it, you'll find that you can safely pull the 42 value back out as an Object and not have any errors at all. The reason for this is that the compiler doesn't insert the cast to String here -- it just inserts a cast to Object (since the left-hand side type is just Object) and the cast from Integer to Object succeeds, as it should.
Anyhow, this is just a bit of a long-winded way of explaining that type erasure doesn't erase all references to the given type, only the type parameter itself.
And in fact, as a now-deleted answer here mentioned, you can exploit this "vestigial" type information, through a technique called Gafter's Gadget, which you can access using the getActualTypeArguments() method on ParameterizedType.
The way the gadget works is by creating an empty subclass of a parameterized type, e.g. new TypeToken<String>() {}. Since the anonymous class here is a subclass of a concrete type (there is no type parameter T here, it's been replaced by a real type, String) methods on the type have to be able to return the real type (in this case String). And using reflection you can discover that type: in this case, getActualTypeParameters()[0] would return String.class.
Gafter's Gadget can be extended to arbitrarily complex parameterized types, and is actually often used by frameworks that do a lot of work with reflection and generics. For example, the Google Guice dependency injection framework has a type called TypeLiteral that serves exactly this purpose.

Generic method in Java, determine type

I would like to be able to detirmine the return type of my method call at runtime, but I can not seem to be able to get the Type of T.
public <T> T getT()
{
Object t = null;
Class<?> c = t.getClass();
System.out.println(c.getName());
return (T) t;
}
Is there any way to determine the Type of T at runtime in Java?
Your function will throw a NullPointerException, because you call "getClass" on a null pointer (since t is initialized with null). Additionally, generics are used for giving added compile-time type-checking. They do not give you anything special at runtime; generics simply use type Object, but cause the code which uses the generic object to perform implicit casts and also causes the compiler to be aware of how you will use it.
Java generics are a static type checking feature. Attempting to retrieve reflection artifacts from generic parameters is typical of poorly thought out design.
In the question example, there is no guarantee that T is a class or even interface. For example
List<? extends Frogs> list = thing.getT();
If you really want to go down this path (and I strongly suggest you don't, not that I expect you to take any notice), then you can supply a reflection object that is statically related to the generic parameter as an argument:
public <T> T getT(Class<T> clazz) {
Object value = map.get(clazz);
return clazz.cast(value);
}
If you have a generic Class you can write a constructor that takes the type and saves it into a member of your class. This way you can check the Type during runtime. All information that are only in the generics are gone after compiling.

Categories