Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Casting method without knowing what to cast to

Tags:

java

casting

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:

  1. 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
    
  2. Java seems to know that it needs to cast to String, or whatever the type of the variable is. But how does this work?

like image 943
TheCoffeeCup Avatar asked Dec 27 '15 01:12

TheCoffeeCup


1 Answers

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
like image 145
Anthony Raymond Avatar answered Oct 13 '22 00:10

Anthony Raymond