简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM