Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method - "unchecked conversion to conform to T from the type" warning

Tags:

java

generics

If I have the following:

public interface Foo {
   <T extends Foo> T getBlah();
}

public class Bar implements Foo {
   public Bar getBlah() {  
      return this;
   }
}

I get a warning in eclipse about the 'getBlah' implementation in class Bar:

- Type safety: The return type Bar for getBlah from the type Bar needs unchecked conversion to conform to T from the type 
 Foo

How can I fix this? And why am I getting the warning?

Thanks

like image 341
Joeblackdev Avatar asked Feb 21 '12 16:02

Joeblackdev


3 Answers

You are overriding a method from your interface, so your implementation you should match the signature from your specification:

public class Bar {
    @Override
    public <T extends Foo> T getBlah() {  
        return this;
    }
}

Now, if you were instead planning on creating a specifically parametized override of the entire implementation, then you need to specify the generic type as a part of the interface definition:

public interface Foo<T extends Foo<T>> {
    T getBlah();
}

public class Bar implements Foo<Bar> {
   @Override
   public Bar getBlah() {  
      return this;
   }
}
like image 133
Perception Avatar answered Nov 04 '22 17:11

Perception


<T extends Foo> T getBlah();

means that a caller can request any type as T to be returned. So no matter what class the object is, I can request some other random subclass of Foo of my choosing to be returned. The only value that such a method could validly return is null (unless it does unsafe casts), which is probably not what you want.

like image 25
newacct Avatar answered Nov 04 '22 15:11

newacct


I am not sure what do you want to accomplish here but I think that returning Foo would be OK:

interface Foo {

  public Foo getBlah();

}

as you are not using the generic type anywhere in the parameters.

like image 3
Alessandro Santini Avatar answered Nov 04 '22 16:11

Alessandro Santini