Mauricio
Mauricio

Reputation: 206

Cast Argument for abstract method with Type parameter

I don't know if its completely possible to do this, but here it goes.

I have an abstract class. Lets call it class 'A'. It looks like this:

public abstract class A <E, T>

It also has the following abstract method.

public abstract Object getEntityId(E entity);

So I can create more classes extending the A class as long as I implement the abstract getEntityId method. For example a class called 'ExtendedA'.

But also I have a secondary class, called it B. It's not abstract and goes like this :

public class B<T> 

(notice the type parameter)

B has a field of type A, which should be an extended class of A (such a ExtendedA). It also contains a List of T such as this:

private A<?,?> myA;
private List<T> myList;

At some point, I need to invoke the abstract getEntityId method in class B for every element in myList, but I can't quite get the cast correctly. I feel like I'm missing something really basic.

for (T t : myList) {
    if (myA.getEntityId(t)!=null) {//does not compile and I can't grasp how should I cast it.
                        
    }
}

Thanks in advance.

Upvotes: 0

Views: 227

Answers (2)

Balaji Murugesan
Balaji Murugesan

Reputation: 49

In order for the code to work, Make it a complete getter method than trying to set value in runtime as it is completely illegal to do it on a wildcard. Either pass the reference private A myA or private A<(some known reference),?> myA or remove the parameter from myA.getEntityId(t)

Also declare a anonymous class and implement the method before calling the method getEntityId()

public class B<T>{

private A<T,?> myA;
private List<T> myList;

public void anycall(){

    for (T t : myList) {
    if (myA.getEntityId(t)!=null) {

    }
}

}
}

Upvotes: 0

Andy Turner
Andy Turner

Reputation: 140319

If your B class looks like this:

public class B<T> {
  private A<?,?> myA;

  void someMethod() {
    for (T t : myList) {
      if (myA.getEntityId(t)!=null) {
      }
    }
  }
}

Then sure, it won't compile: the parameter of getEntityId is ?, and you're trying to pass it a T. ? doesn't mean "any type", it means "a specific type, just one that I don't know".

To pass a T to getEntityId(), the first type parameter of A needs to be T:

  private A<T,?> myA;

Upvotes: 2

Related Questions