• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Jj Roberts
  • Carey Brown
Bartenders:
  • salvin francis
  • Frits Walraven
  • Piet Souris

How to overload generic method for specific type of template argument

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am porting C++ application to java and I have a problem with Genric method.

I have generic class which should implement functionality depending on template argument.


T should wrap plenty of different types of types and they differe in way to stream. Only method which is specific to each type is "saveToStream".
In C++ it is very easy:


As a solution I have created set of saveToStream() methods (for every type of parameter) and the same set of subclasses of generic class. It is "ugly" comparing to C++. Is there something more elegant?

BR
 
Sheriff
Posts: 22053
113
Eclipse IDE Spring VI Editor Chrome Java Ubuntu Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java also knows generics, but only for objects - not for the primitive types. You can use the wrapper classes however: TypeWrapper<Integer>.
 
Dorian Gray
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I did it but it does not solve problem. I still need declaration of method for every argument type (primitive or wrapper around primitive)

This is copy of C++ code:


and finaly implementation for every type parameter:


In java I have to create classes for each object type I am using (Int, Boolean, String,...) and same number of methods:

Curently 8 new classes and 8 method overloads while in C++ only 8 methods are overload.

It would be good if I can create one method only where compiler will realize which concreate class to use

BR
 
Bartender
Posts: 11445
19
Android Google Web Toolkit Mac Eclipse IDE Ubuntu Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Dorian Gray",
Please check your private messages for an important administrative matter.
 
Any sufficiently advanced technology will be used as a cat toy. And this tiny ad contains a very small cat:
the value of filler advertising in 2020
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic