Obtain class of Generic type? (how can I remove a Class<T> parameter)

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?
 
M

moongate

AFAIK, Java has no notion of generic programming, methods, or classes.
If I understand correctly, what you might want to do for your code
above is get rid of your if-else' chain and actually write multiple
methods of the form:

public String asString(Object obj) throws ClassCastException {
if(obj instanceOf String)
return (String)obj;
else throw new ClassCastException();
}

Since the JVM can throw ClassCastException all by itself when you try
an illegal cast, this in turn could be rewritten as follows:

public String asString(Object obj) throws ClassCastException {
return (String)obj; // let JVM throw the exception as needed
}

But then, this method looks pretty useless to me, i.e., the expression

asString(obj)

becomes basically the same as
(String)obj

so it seems the method doesn't buy you much....

MC
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top