I was playing around with Java today, and I noticed something weird. Consider this code:
String foo = cast("hi");
int bar = cast("1");
The cast()
method is here:
public static <T> T cast(Object value) {
return (T) value;
}
Java seems to cast "hi"
to a String, even if I didn't pass any hint that it would be a String
, with the exception of the type. It does foo
well, but fails on bar
, because you can't case a String to an Integer. What is happening here?
I have two guesses:
The cast method is returning an Object
, and at initialization it automatically casts to the type.
This doesn't make sense, as it would give me:
Type mismatch: cannot convert from Object to int
Java seems to know that it needs to cast to String, or whatever the type of the variable is. But how does this work?
public static <T> T cast(Object value) {
return (T) value;
}
The important part is the <T>
on the method, it means that the method will return a type based on what the method call expect.
String foo = cast("hi"); // left side is a String, <T> will be typed as String
The second is a bit more tricky since Generic types cannot be primitive types. I guess it returns the most common type Object
.
int bar = cast("1"); // left side is primitive
// <T> will be typed by with the corresponding non-primitive type.
// But it fails because "1" cannot be casted to java.lang.Integer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With