Java Generators Extending Return Method Type

Take a look at these three classes. Minatchi allows you to extend it, so that its return type of methods can also be extended. For illustration, I used the static method.

public class Minatchi<T extends Minatchi<?>>{

  static public <T extends Minatchi<?>>
    List<T> listAll(){
      return
        (List<T>) query();
  }
}

And so I subclass Minatchi in Lady

public class Lady
extends Minatchi<Lady>{

}

This is where dubious behavior occurs.

public class HelloMinatchi{

  private void listA(){
    List<Lady> uvs = Lady.listAll();
    for (Lady uv: uvs){
      logger.info(uv.getName() );
    }
  }

  private void listB(){
    for (Lady uv: Lady.listAll()){
      logger.info(uv.getName() );
    }
  }
}

The list of methods A and listB are essentially the same. listA puts the list in the uvs intermediate variable, while listB directly puts listAll in the for-loop header.

However, for listB, the compiler complains. Can't Convert Minatchi <? > at Lady.

So this question is about the integrity of the design of Java generics. Another generic.

, Java , . , ? , ?

, ? , , .

( Minatchi, , , .)

+5
4

. .. listAll() Lady ( extends Minatchi<Lady>).

:

  • listA() , List<Lady>
  • in listB() forEach , Lady, , , forEach.

listB() , , :

for (Lady uv : Lady.<Lady>listAll()) {..}
+5

, listAll, , , . "" , :

for (Lady uv: Lady.<Lady>listAll()){
    logger.info(uv.getName() );
}

, , Minatchi , .

, Lady.listAll , Minatchi.listAll(.. , ).

+1

, : ?, Java .

. .

+1

- .

Java Generic tutorial

, , - a , , .

Lady.ListAll Minatchi, , - Minatchi

, Java, , . , reification ​​ Java, Java 7.

+1

All Articles