Java Casting method without knowing what to cast to
问题 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