Java User
Java User

Reputation: 33

Java Generics - Using the generic type parameter of the enclosing class in a method parameter

I've a simple generic class follows which accepts a generic type parameter, which is the same as the one declared as a type parameter of the class:

import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;

public abstract class SimpleClass<T extends AnnotatedElement>
{

   public void operate()
   {
      Method m = null;
      this.doSomething(m); // Error : SimpleClass.java:[34,10] doSomething(T) in SimpleClass<T> cannot be applied to (java.lang.reflect.Method)
   }
   protected abstract void doSomething(T annotatedElement);
}

This code fails to compile at the following line:

this.doSomething(m); 

with this error:

Error : SimpleClass.java:[34,10] doSomething(T) in SimpleClass<T> cannot be applied to (java.lang.reflect.Method)

Am I missing something here? The type parameter T is marked as T extends AnnotatedElement. As such, I would expect the call to doSomething with a java.lang.reflect.Method argument to compile successfully.

Upvotes: 2

Views: 1046

Answers (4)

Umesh Kacha
Umesh Kacha

Reputation: 13666

Your generic method is not implemented correctly. Change your generic method to

protected abstract<T extends AnnotatedElement> void doSomething(T annotatedElement);

Above statement creates correct generic method. This will remove compilation error.

Upvotes: 0

Jeremy
Jeremy

Reputation: 22415

This is because T doesn't matter here. All you know is that the type is AnnotatedElement.

The following change would make it compile:

 protected abstract void doSomething(AnnotatedElement annotatedElement);

Upvotes: 0

Erik
Erik

Reputation: 91270

There's no way to know that T is a Method. It could just as well be e.g. a Package, and then your operate() wouldn't make sense, trying to pass a Method to something expecting Package

Upvotes: 0

David Yaw
David Yaw

Reputation: 27864

Method implements AnnotatedElement, but that doesn't require that T is a method. What if the class is declared as SimpleClass<Constructor>? That satisfies <T extends AnnotatedElement>, but doesn't support conversion from Method.

Upvotes: 2

Related Questions