Search code examples
javaguice

Is it possible to inject dependency inside java interface using guice - java


I am trying to inject dependency inside my interface

public interface TestInject {

   @Inject
   Mydependency dependencyToCall;

    default void processInput(String inputToCheck) {
        //some lines of code
        dependencyToCall.process(inputToCheck)
    } // If i dont do this then all implementation has to implement same code. 

  void handleError()//will be overwritten by implementation class

}

the above code throws error variable dependencyToCall might not be initialized

Is it possible to inject inside interface ?

Or do i have to introduce abstract class to solve redundant code issue


Solution

  • I think it will not work. Check the official document about Java Interface, here:

    An interface declaration introduces a new reference type whose members are classes, interfaces, constants, and methods. This type has no instance variables, and typically declares one or more abstract methods; otherwise unrelated classes can implement the interface by providing implementations for its abstract methods. Interfaces may not be directly instantiated.

    Guess you should change to use abstract class