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
|