简体   繁体   中英

Using generic method parameters in Java

I'm trying to use generic methods in java for the first time. It isn't working, and it appears to me that Java generics are simply not meant to be used this way - that I will need to implement a common interface rather then using a generic method. Please confirm (or deny) that conclusion.

This is what I'm trying to do:

public <T> void updateItem( T item ) {
  String itemKey = item.getKey();
  ...

This gives me the error 'The method getKey() is undefined for the type T'.

Looking into why this doesn't work I see that type erasure "replaces all type parameters in generic types with their bounds or Object if the type parameters are unbounded".

The only way I can 'bound' my type T is if I create a common subclass or interface for all the types I was planning to use, and if I do that then I can use polymorphism rather then generics.

This is right. Method getKey() is not defined in class T . However if you define your method as following:

public <T extends Entry> void updateItem( T item ) {
  String itemKey = item.getKey();

the compiler can find getKey() method. Please pay attention that I used <T extends Entry> (I mean java.util.Map.Entry ). This class has method getKey() and compiler can resolve it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM