I play with some ideas about creating a Java API, and today I thought about this code for a while:
public <T> T getField1(Class<?> type, Class<T> retvalType, String fieldName) {
Object retval = ...;
return retvalType.cast(retval);
}
int foo = getField(o, Integer.class, "foo");
This is how I usually write the API, if not for the idea that the indication retvalTypegives me extra type safety. But does?
Since we have reflection, the type retval is unknown. Casting in the second line will reliably track type mismatch only when it retvalTypeis nonequivalent. On the other hand, even if we do not make this explicit cast, the Java runtime will generate a general result when it sets it to a variable - in other words, are there any flaws if we rewrite the above code as:
public <T> T getField2(Class<?> type, String fieldName) {
return ...;
}
int foo = getField(o, "foo");
, , . , ( ), , - , , , - .
- , ?
1:
, , , API.
, Date, long, , date.getTime(). , .
, , API . (Cue " ", " " ..).