oop - Java generics and typecasting -


i have badly created container object holds values of different java types(string, boolean etc ..)

public class badlycreatedclass {     public object get(string property) {         ...;     } }; 

and extract values in way

string mystr = (string) badlycreatedobj.get("abc"); date mydate = (date) badlycreatedobj.get("def"); 

i forced write new code using object , trying see if there clean way this. more method below preferred ?

explicit cast

string mystr = (string) badlycreatedobj.get("abc") date mydate = (date) badlycreatedobj.get("def"); 

using generic cast

public <x> x genericget(string property) {  }  public string getstring(string property) {  return genericget(property);  }  public date getdate(string property) {  return genericget(property);  } 

using class.cast

<t> t get(string property, class<t> cls) {     ; } 

i have gone through several related questions on java generic function: how return generic type , java generic return type of them seem such typecasting dangerous, although dont see difference between three, given method prefer ?

thanks

to give quick answer, without going in deep good-programming-practice...

i use:

private <x> x genericget(string property) {  }  public string getstring(string property) {  //... checks on property (string specific)... object obj = genericget(property); //... checks if obj expected , if return return obj;  }  public date getdate(string property) {  //... checks on property (date specific)... object obj = genericget(property); //... checks if obj expected , if return return obj } 

make notice private genericget. way can check if property m waiting receive , handle in correct way.

i add checks in getstring depends on property make sure answer string object.

i other checks getdate in property make sure date returned.

etc...


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -