Search code examples
javadependency-injectionrcp

Using ContextInjectionFactory with Type <T>


What is the correct way to use DependencyInjection / ContextInjectionFactory without generating a type safety warning?

 public class MyClass<T> {...}

 // Without Dependency Injection
 MyClass<MyType> x = new MyClass<MyType>();

 // With Dependency Injection and TypeSafety warning
 MyClass<MyType> x = ContextInjectionFactory.make(MyClass.class, context);

Solution

  • Your going to have to use the wild card generic <?>.

    MyClass<?> x = ContextInjectionFactory.make(MyClass.class, context);
    

    This will remove the warning but then all generic methods will only work with Object. One way around this is to cast x to MyType.

    MyClass<MyType> myClass = (MyClass<MyType>) x;