Re: Force a class to have certain static methods
Chris wrote:
How do I force a class to have certain static methods?
Here's the problem. Our system has certain pluggable classes. To make a
new implementation of such a class, you just have it implement a certain
interface.
I want to have these classes have certain static methods like getName()
and getDescription() that just return constants. The trouble is, you
can't put static methods in an interface. You also can't have static
abstract methods.
I could make these methods non-static, but then you'd have to actually
create each class just to get its description, and that's an expensive
process. The classes can contain data structures that are quite large.
What's the workaround?
If you are free to make major changes, you could go to a factory system,
and put the description etc. in the factory. Suppose your pluggable
interface is XXX:
interface XXXFactory{
XXX getInstance();
String getName();
String getDescription();
}
An XXXFactory would be cheap to create, and required to have the
methods. You would get an instance of the actual plug-in by calling the
factory's getInstance method.
If you cannot do something like this, or do not think it would make
sense in your context, consider leaving the static methods optional, and
providing defaults if the method does not exist, such as using the class
name for the getName() and getDescription() results. If the user wants a
more descriptive name, it is up to them to supply the static method.
Patricia