0

I have a static method in my base class:

private static <T extends BaseClass<? super T>> T getIt(Class<T> theClass, T obj)
{ ... }

I want to have an instance method in the base class that can pass this to that method:

public <T extends BaseClass<? super T>> T getSelfChanged()
{
    T changedSelf = getIt( getClass(), this );
}

But the use ofthis throws the error:

Wrong 2nd argument type. Found BaseClass<T> required "? extends BaseClass"

Trying to cast it, doesn't work either:

//DOESN'T WORK
T changedSelf = getIt( getClass(),  ( T ) this );

How do I make this work?

Don Rhummy
  • 24,730
  • 42
  • 175
  • 330
  • 1
    How are you expecting to pass `this` to the method when `this` is of type `BaseClass` and the method expects `T extends BaseClass` ? – explv Jun 20 '16 at 16:56
  • @arizzle because `this` in a base class can be cast to the child class' type. If I were to return `this` in a method as an object, I could cast it to the child class because that's what the object is. – Don Rhummy Jun 20 '16 at 16:58
  • Downcasting isn't allowed in Java. You cannot downcast from `BaseClass` to `T extends BaseClass`. – explv Jun 20 '16 at 17:00
  • @arizzle Why doesn't this alternative work? `public > T getSelfChanged(T self)` – Don Rhummy Jun 20 '16 at 17:01
  • you would need to pass the class of `T` as well, this would work for example: `public > T getSelfChanged(Class clazz, T self) { T changedSelf = getIt(clazz, self); }` – explv Jun 20 '16 at 17:10

0 Answers0