Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics Conundrum

Tags:

java

generics

Here's the relevant code:

public interface Artifact {}    
public interface Bundle implements Artifact {}
public interface Component implements Artifact {}

public interface State<T extends Artifact> {
    void transition(T artifact, State<T> nextState);
}

This allows me to define this enum:

enum BundleState implements State<Bundle> {

    A, B, C;

    public void transition(Bundle bundle, State<Bundle> nextState) {}
    }
}

But the method signature that I want is:

    public void transition(Bundle bundle, BundleState nextState) {}
    }

But this does not compile. Obviously the problem lies with how I've defined T in the State interface, but I can't figure out know how to fix it.

Thanks, Don

like image 554
Dónal Avatar asked Dec 09 '22 13:12

Dónal


1 Answers

Things might start getting unwieldly, but you could change State to:

public interface State<T extends Artifact, U extends State<T, U>> {
    void transition(T artifact, U nextState);
}

And change BundleState to:

public enum BundleState implements State<Bundle, BundleState> {
    A, B, C;

    public void transition(Bundle bundle, BundleState nextState) {}
}
like image 91
Kirk Woll Avatar answered Dec 13 '22 22:12

Kirk Woll