• Post Reply Bookmark Topic Watch Topic
  • New Topic

better / smarter way to use generics to build a collections-type class  RSS feed

 
Rancher
Posts: 4686
7
Linux Mac OS X VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm building a "SmartList" the details of what make it smart are not all that important, but as with other List/Map/Set code, it should use generics.
Inside the implementation, I need to find the type that was used, so I can call functions of the classes that implement the type.

I can't find a clean way to do this, other than passing the class in as an explicit argument to the constructor, and saving it.



To my eyes, this is ugly, as there are three copies of the word "Phone" in line [2]
and one of these days, someone will change it in two places and leave one wrong.

Is there a better way to approach this?

thanks
pat

 
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since generic types are erased at compile time, so you have to pass Phone.class to the constructor. You can get rid if the SmartList<Phone> though and have the type be infered by the compiler.
 
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pat Farrell wrote:someone will change it in two places and leave one wrong.

Which will lead to a compiler error if you code it right:
A SmartPhone<Phone> reference must be instantiated using a SmartPhone<Phone>(Phone.class) call, as anything else simply will not compile.

You can get rid of one of the <Phone>s by using type inference:
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!