Announcement Announcement Module
Collapse
No announcement yet.
Factory Method with Generic Types Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Factory Method with Generic Types

    I have the following classes:
    Code:
    @Component
    public FordFactory extends CarFactory<Ford> {
      public FordCar getInstance() {
        return new FordCar();
      }
    }
    
    public abstract <T extends Car> CarFactory<T> {
      public abstract T getInstance();
      protected boolean utilMethod(Object obj) {
        return null == obj;
      }
    }
    and the following bean definition:
    Code:
        <bean id="fordCar"
              factory-bean="fordFactory"
              factory-method="getInstance" />
    When I start my application server, I get a NoSuchBeanDefinitionException. Through debugging, I found that ReflectionUtils.getAllDeclaredMethods(FordFactory) returns an array that contains three versions of getInstance():
    1. public FordCar FordFactory.getInstance()
    2. public java.lang.Object FordFactory.getInstance()
    3. public java.lang.Object CarFactory.getInstance()
    The first is correct, attached to FordFactory and returning FordCar. The other two both return Object, one attached to FordFactory and the other attached to CarFactory. Because between the three methods, two different return types are found, Spring throws up its hands and declares that the type of the bean can't be determined.

    Is the behavior of a bean factory extending a generic abstract class not allowed? Why wouldn't the factory method just be called to instantiate a new bean, letting the type be determined by reflection on the instance rather than on the return type of the method?

    Explicitly noting the type of the bean in the bean definition XML doesn't help. Removing the abstract parent classes removes the extra two method references (the ones returning Object) returned by ReflectionUtils, allowing the bean to instantiate. But this isn't ideal, since I structured my classes that way for a reason.
    Last edited by bpholt; Jun 14th, 2011, 06:57 PM. Reason: added comment about refactoring to remove inheritance
Working...
X