M
mortoray
I have some code (below) that does a custom conversion between types
(namely from an Object type to some specific type). It is a prime
candidate for Generics (to avoid the return value casts by the user),
but there doesn't appear to be any way to get rid fo the Class<T>
parameter -- that is, the type I wish still needs to be a formal
parameter and not just the Generic Type.
/** @param type - the type to conver to
* @param obj - the obejct to convert */
static public <T> T asType( Class<T> type, Object obj ) throws
Exception {
if( type.equals( Number.class ) )
return type.cast( asNumber( obj ) );
if( type.equals( String.class ) )
return type.cast( asString( obj ) );
if( type.equals( OutputStream.class ) )
return type.cast( asOutputStream( obj ) );
if( type.equals( InputStream.class ) )
return type.cast( asInputStream( obj ) );
if( type.equals( Boolean.class ) )
return type.cast( asBoolean( obj ) );
return null;
}
If I understand generics correctly it woult not be possible to create
an Object of Class<T> type within the routine since the T is actually
not specified at run-time. But is there some other way to get rid of
the formal "type" parameter and make this work?
(namely from an Object type to some specific type). It is a prime
candidate for Generics (to avoid the return value casts by the user),
but there doesn't appear to be any way to get rid fo the Class<T>
parameter -- that is, the type I wish still needs to be a formal
parameter and not just the Generic Type.
/** @param type - the type to conver to
* @param obj - the obejct to convert */
static public <T> T asType( Class<T> type, Object obj ) throws
Exception {
if( type.equals( Number.class ) )
return type.cast( asNumber( obj ) );
if( type.equals( String.class ) )
return type.cast( asString( obj ) );
if( type.equals( OutputStream.class ) )
return type.cast( asOutputStream( obj ) );
if( type.equals( InputStream.class ) )
return type.cast( asInputStream( obj ) );
if( type.equals( Boolean.class ) )
return type.cast( asBoolean( obj ) );
return null;
}
If I understand generics correctly it woult not be possible to create
an Object of Class<T> type within the routine since the T is actually
not specified at run-time. But is there some other way to get rid of
the formal "type" parameter and make this work?