The following code is from an Android library called ButterKnife. I'm figuring out how it works.
@SuppressWarnings("unchecked") // That's the point.
public <T> T castParam(Object value, String from, int fromPosition, String to, int toPosition) {
try {
return (T) value;
} catch (ClassCastException e) {
throw new IllegalStateException("Parameter #"
+ (fromPosition + 1)
+ " of method '"
+ from
+ "' was of the wrong type for parameter #"
+ (toPosition + 1)
+ " of method '"
+ to
+ "'. See cause for more info.", e);
}
}
I tried to recreate the behaviour of this function:
@SuppressWarnings("unchecked")
public static <T> T cast(Object o){
try {
return (T) o;
} catch (ClassCastException e){
throw new AssertionError("Error");
}
}
And usage:
Object o = new String("test");
Double d = cast(o);
But the exception is not never caught, it gets thrown at the line when the method is called. Why is that?
Also, how does this work exactly? How does the method know what to cast to?