Re: Generic Trouble
Andreas Leitgeb wrote, quoted or indirectly quoted someone who said :
First of all, the generic class will *not* know the actual
type used. At most you can enforce it to be a subclass or
superclasses of some given class.
Roedy Green wrote:
If you to know the actual class, you will have to pass that as an
explicit class parameter somewhere, or find out the class dynamically
with getClass. Remember that all information about generics is washed
away by the compiler so at runtime, it is as if no generics were used.
All generics can really do is some additional cross-checks on how you
use combinations of classes, taking into consideration only
information that can be gleaned from types known at compile time.
Exactly so.
Let us not disparage "all [that] generic can really do", though. It is
significant. Once you get your type assertions right for the compiler, it is
impossible to have class-cast problems at run time. Also, the need to know
run=time type information is much rarer than one might think, if all the type
assertions are correct at compile time. Properly used, generics lock down a
program to a significantly more stable state.
When you do need type information at run time, one standard idiom is that
class parameter Roedy mentioned, a runtime type token (RTTT) similar to
(appropriate imports and static imports assumed):
/**
* Foo illustrates a run-time type token (RTTT).
* @param <T> base type of class.
*/
public class Foo <T>
{
private final Logger logger = getLogger( getClass() );
private final Class <T> rttt;
/**
* Constructor with run-time type token.
* @param tok Class {@code <T>} type token.
*/
public Foo( Class <T> tok )
{
if ( tok == null )
{
final String msg = "Run-time type token must not be null";
IllegalArgumentException fubar = new IllegalArgumentException( msg );
logger.error( msg, fubar );
throw fubar;
}
this.rttt = tok;
assert this.rttt != null;
}
// ... rest of the class
}
You can use the methods of 'rttt' to cast, check compatibility and do other
run-timey type thingies.
--
Lew