I am running into a strange problem. I have an interface, whose implementations tend to be stateless. So, I want them to be singletons.
I get the implementation class names as strings. For example
String clazz = "com.foo.Bar";
I have a rules factory to obtain instances of IRule implementations.
public class RulesFactory {
private static final Logger logger = LoggerFactory.getLogger(RulesFactory.class);
@SuppressWarnings("unchecked")
public static <T extends IRule> T getRuleInstance(String clazz) {
try {
Class<?> ruleObject = Class.forName(clazz);
Method factoryMethod = ruleObject.getMethod("getInstance");
return (T) factoryMethod.invoke(null);
} catch (ClassNotFoundException e) {
logger.error("ClassNotFoundException", e);
} catch (IllegalAccessException e) {
logger.error("IllegalAccessException", e);
} catch (SecurityException e) {
logger.error("SecurityException", e);
} catch (NoSuchMethodException e) {
logger.error("NoSuchMethodException", e);
} catch (IllegalArgumentException e) {
logger.error("IllegalArgumentException", e);
} catch (InvocationTargetException e) {
logger.error("InvocationTargetException", e);
}
return null;
}
}
The above code throws NullPointerException if the class doesn't have a static getInstance() method. In Java 6 i can't use static methods in interfaces. I don't want to create multiple instances of IRule implementations. If I can enforce a static method and invoke that static method I will get the cashed instance. But I am unable to do this. How to solve this problem?
getInstance()methods.