Class HandlerFactory
This factory uses reflection to discover all RequestHandler subclasses
in the com.ns package at application startup and caches them for efficient
instantiation. Handlers can be retrieved by either their simple class name or
fully qualified class name.
The factory performs the following operations:
- Scans the
com.nspackage for all RequestHandler subclasses at class loading time - Caches discovered handlers in a map for O(1) lookup by name
- Provides both simple name (e.g., "StaticFileHandler") and fully qualified name (e.g., "com.ns.tcpframework.reqeustHandlers.StaticFileHandler") lookup
- Instantiates handlers dynamically using reflection with no-arg constructors
This pattern enables configuration-driven handler registration, allowing route configurations to specify handlers by string name rather than requiring hardcoded instantiation.
Example usage:
RequestHandler handler = HandlerFactory.getRequestHandlerByName("StaticFileHandler");
// or
RequestHandler handler = HandlerFactory.getRequestHandlerByName("com.ns.tcpframework.reqeustHandlers.StaticFileHandler");
Thread-safety: This class is thread-safe after initialization. The static cache is populated once during class loading and is read-only thereafter.
- See Also:
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic RequestHandlergetRequestHandlerByName(String className) Creates and returns a new instance of a RequestHandler by class name.
-
Constructor Details
-
HandlerFactory
public HandlerFactory()
-
-
Method Details
-
getRequestHandlerByName
Creates and returns a new instance of a RequestHandler by class name.This method looks up the handler class in the cache using the provided name (which can be either a simple name or fully qualified name) and instantiates it using reflection. Each call creates a new instance of the handler.
Supported name formats:
- Simple name:
"StaticFileHandler" - Fully qualified name:
"com.ns.tcpframework.reqeustHandlers.StaticFileHandler"
Requirements for handler classes:
- Must extend
RequestHandler - Must have a public no-argument constructor
- Must be located in the
com.nspackage or its subpackages
- Parameters:
className- The name of the handler class to instantiate. Can be either the simple class name or the fully qualified class name.- Returns:
- A new instance of the specified RequestHandler class.
- Throws:
ClassNotFoundException- If no handler class with the given name is found in the cache.NoSuchMethodException- If the handler class does not have a no-argument constructor.InstantiationException- If the handler class is abstract or cannot be instantiated.IllegalAccessException- If the no-argument constructor is not accessible.InvocationTargetException- If the constructor throws an exception.Exception- If any other error occurs during handler instantiation.
- Simple name:
-