1

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.

7
  • 1
    What is T supposed to be? You could use <T extends SomeClassWithGetKey> Commented Apr 4, 2013 at 17:06
  • Looks like you want to use an interface, not generics. Commented Apr 4, 2013 at 17:06
  • I have this idea (from Python or C++) that I don't have to specify what T is. T will be type checked when it is invoked with a type. Commented Apr 4, 2013 at 17:07
  • This won't work in Java. Commented Apr 4, 2013 at 17:08
  • @Tom generics are a compile time feature in Java. It is type checked at compile time, not when it is invoked, hence it has to be resolvable at compile time. Commented Apr 4, 2013 at 17:11

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Yeah, I had this idea (from Python and C++) that the compiler wouldn't try to resolve the call until invocation (or runtime in Python) so as long as it worked as used it was fine.
The odd thing (to me) is that, if T has a common base class (Entry above) then I don't need generics at all.
@Tom That's corrent - just have the method take Entry for example. Sometimes polymorphism is enough and you don't need generics.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.