A few years ago I tried to answer this question in a generic way in the RFC Genuine Service Factories. After a lot of hard thought I came to the conclusion that the solution was very simple. Just register a factory service. So if you want to be able to create Foo's, just register a FooFactory service ... This allows you to have all the goodies of parameters, type safety, etc. If want a generic solution, just create a Factory type:
public interface Factory<T> { T create(); }
@Component
public class FooFactoryImpl implements Factory<Foo> {
public Foo create() { ... }
}
However, I found that the nicest way is just to create a FooFactory since this gives you type safety all the way since the generic types tend to require casting. It also gives you extensibility, parameters, and most of all proper documentation of the semantics.
All the other solutions I know tend to suffer from heavy casting and bypassing the type system. The factory components in Declarative Services are a point in case. I think the responsibility of the OSGi service registry is to give you a handle. As with all technologies it is very tempting to add additional semantics since it is often close. I think this is a case that is much better left to Java than to OSGi. keep it simple.