Java Generics Use Case

Viewed 581


I am trying to use Java Generics in this use case and need some help figuring out how to implement it after not finding any answers online. Here is my use case....

// Interface DevObject   
public interface DevObject  { 
    void addExtension(DevExtension extension);
}

// Interface DevExtension 
public interface DevExtension<T extends DevObject> {
    void start(T devObject); 
}

Then I create two classes that implement DevObject and DevExtension respectively like this ...

public class MyDevObject implements DevObject {
      void addExtension(DevExtension extension) {

      }
}


public class MyDevObjectExtension implements DevExtension<MyDevObject> {
     void start(MyDevObject devObject) {

     }
}

But what I really want to do is use generics to modify the addExtension method on DevObject so that it will only be able to add DevExtension instances that have their generic T value to be the same as the class that implements DevObject.

Any help would be appreciated.

1 Answers

You're looking for the CRTP:

public interface DevObject<T extends DevObject<T>> { 
    void addExtension(DevExtension<T> extension);
}

public interface DevExtension<T extends DevObject<T>> {
    void start(T devObject); 
}
Related