Il seguente codice proviene da una libreria Android denominata ButterKnife. Sto scoprendo come funziona.Cast di generici Java in base al tipo restituito?
@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);
}
}
ho cercato di ricreare il comportamento di questa funzione:
@SuppressWarnings("unchecked")
public static <T> T cast(Object o){
try {
return (T) o;
} catch (ClassCastException e){
throw new AssertionError("Error");
}
}
e di utilizzo:
Object o = new String("test");
Double d = cast(o);
Ma l'eccezione non viene mai preso, ma si butta in linea quando il il metodo è chiamato. Perché?
Inoltre, come funziona esattamente? In che modo il metodo sa a cosa lanciare?
Qui qualcun altro ha cercato di fare esattamente la stessa cosa: http://stackoverflow.com/questions/14524751/cast-object-to-generic-type-for-returning – SJuan76
Come funziona allora la libreria? – Greyshack