• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

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

 
Rancher
Posts: 4686
7
Mac OS X VI Editor Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 22683
128
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:
 
Good night. Drive safely. Here's a tiny ad for the road:
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic