Вопрос

I do have an abstract class with an delegation interface defined:

public abstract class MyAbstractClass extends AsyncLoader {

public interface MyAbstractClassDelegate<M> {
    //The parameter in this method should be the concrete subtype of MyAbstractClass
    public M performThisCall(MyAbstractClass concreteSubclassOfAbstractClass);
}

private MyAbstractClassLoaderDelegate delegate;
    ...
}

The Problem is, I do not want the delegate parameter to be MyAbstractClass, instead it should be the concrete subclass. Why? Because the implementation of the delegate needs the concrete subclass for further handling and I don't want to cast it...

I know I could define an Interface in each subclass, but it'll look the same in every subclass except for the parameter type

EDIT

Here is the perfect solution solving exactly what I wanted. Great thanks!

public abstract class MyAbstractClass {

public interface MyAbstractClassDelegate<M, Subtype extends MyAbstractClass> {
    public M myMethod(Subtype t);

}

}

Is this possible with java 6 and if yes - how?

Это было полезно?

Решение

My solution would be:

public final class Example<T extends Example<T>> {

    public interface Interface<M, Subtype extends Interface<M, Subtype>> {
        public M myMethod(Subtype t);

    }
}

You have no access to the generic from the outer class inside the interface (because the interface is static) so you have to declare it again.

If you use your interface you get something like this:

private static class Impl1 implements Interface<String, Impl1> {

  @Override
  public String myMethod(final Impl1 t) {
    return null;
  }
}

I don't know if it will help but here is my complete example:

public final class Example<M, T extends Example.Delegate<M, T>> {

  public interface Delegate<M, Subtype extends Delegate<M, Subtype>> {
    public M myMethod(Subtype t);
  }

  private T delegate;


    private static class Impl1 implements Delegate<String, Impl1> {

      @Override
      public String myMethod(final Impl1 t) {
        return null;
      }

  }

  public static void main(String[] args) {
    Example<String, Impl1> example =  new Example<>();
    example.delegate = new Impl1();
    example.delegate.myMethod(example.delegate); //works but whout?
  }
}

Другие советы

What you could do is to give your abstract class a type parameter with the concrete subclass, similar to the way Java's Enum does it.

Something along the lines of this:

public abstract class MyAbstractClass<S extends MyAbstractClass<S>> extends AsyncLoader {

    public interface MyAbstractClassDelegate<M, S> {
        public M performThisCall(S concreteSubclassOfAbstractClass);
    }

...
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top