Re: How to pass class type argument?
Allen wrote:
In my PluginRegisterManager class, there is a Vector registerVector
which stores all kinds of registered handlers as Object type. So I
need to get specified kind of handlers, i.e.
PluginFileHandler[] handlers = manager.getPluginFileHandler();
Because registerVector is defined as:
Vector<Object> registerVector;
Then if I want to get paint handlers, I have to write exactly the same
codes as getPluginFileHandler() except check instanceof
PluginPaintHandler.
How to use class type as argument? If this is feasible, I just need
only one function named getHandler(<classtype>).
As far as I understand it, you are storing many different kind of
handlers in a vector and you want to be able to retrieve those handlers
without writing separate getHanderXX() functions for each type of
handler, correct.
The easy answer is you can use generics for this. All classes need to
have a common super class or implemented interface and then you specify
the that common class or interface as the type for the vector and the
get method. e.g.
class PluginHandler {}
class FilePluginHandler extends PluginHandler {}
Vector<? extends PluginHandler> registerVector
or just
interface PluginHandler {}
Vector<PluginHandler> registerVector;
the method is in any case:
<PluginHandler> getHandler()
The difficult part is how do you know what data is being returned to
you, since the vector can store any type. To solve that, every handler
should implement some common methods specified in the interface or
superclass. And make sure you only use the methods defined in the common
interface to handle the handlers. That way it does not matter which type
of handler it is, because the interface will take care of it for you.
This is what is known as programming to interfaces. Have a look at the
List interface (in the API doc) and then at all the specific
implementations of the List interface. It will help you understand it
better.
tom