Win a copy of Murach's Java Programming this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to overload generic method for specific type of template argument  RSS feed

 
Dorian Gray
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
 
Rob Spoor
Sheriff
Posts: 21019
84
Chrome Eclipse IDE Java 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
 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Dorian Gray",
Please check your private messages for an important administrative matter.
 
You don't like waffles? Well, do you like this tiny ad?
Thoughts on deprecation in Java
https://coderanch.com/t/683016/java/Deprecation-Java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!