Java Generics are Not that Generic

For example something like this:

template<T> void doSomething(T t)
{
  t.doTheWork();
}

Is invalid, because Sun's implementation only allows you to call the methods that are on the Object class. So, instead you have to do something like this:

interface DoWork
{
   void doTheWork();
}

template<T extends DoWork> void doSomething(T t)
{
  t.doTheWork();
}

Thanks to Bruce Eckle for pointing this out.

Updated: Dare has a good list of reasons for this (turns out the C# team made the same decision)

2 Comments

  • It would be more interesting to read about the tradeoffs behind that design decision, and why you disagree with the choices made, avoiding emotive terms like &quot;morons at Sun...&quot;, &quot;lame design decision&quot;

  • C# is the same as Java in this case.



    Having T implement an interface that lists &quot;doTheWork&quot; helps for type safety. Just because a class happens to have a method called &quot;doTheWork&quot; doesn't mean that it is meant to be used this way.



    There is a similar debate with delegates vs. inner classes.

Comments have been disabled for this content.