java - How to handle arbitrary user supplied types in my library? -


i'm writing library able handle hexagon grids.

the user has access hexagongridbuilder object can set width, height , lot of other parameters grid , build() method returns hexagongrid object. hexagongrid has various methods hexagon (for example grid coordinate, or pixel coordinate).

my problem want allow user put arbitrary satellite data in each hexagon object on hexagongrid. best practice so?

i can provide generic methods allow user pass satellite data hexagon:

private object satellitedata;  public <t> void setsatellitedata(t satellitedata) {     this.satellitedata = satellitedata; }  @suppresswarnings("unchecked") public <t> t getsatellitedata() {     return (t) satellitedata; } 

this flawed since involves casting objects without being sure type is.

i can modify hexagongridbuilder user can pass class object satellite data can validate whether supplied right type or not:

   public <t> void setsatellitedata(t satellitedata) {     if (!satelliteclass.isassignablefrom(satellitedata.getclass())) {         // throw exception     }     this.satellitedata = satellitedata; } 

but still involve unchecked casts in getsatellitedata() method:

@suppresswarnings("unchecked") public <t> t getsatellitedata() {     return (t) satellitedata; }' 

the right soulution seems making whole library generic have generic parameter satellite data type involves making every class involved generic:

hexagongrid<satellite_data_type> hexagongrid = new hexagongridbuilder<satellite_data_type>().build(); 

so i'm not sure 1 choose. least hacky solution? or there else did not think about?

edit: wish know is worth trouble make of involved classes generic (which make them harder understand , bit messy) or can away 2 generic methods , plus method in builder supply class? reason is possible user won't use satellite data fuss , feathers.

you need place <t> type parameter on entire hexagongrid class, not on methods. can define field private t satellitedata, eliminate <t>s on methods, , remove explicit cast. approach talked last.

if there's reason want use builder rather constructor, don't have genericize builder; pass in type parameter build method. see enumset#noneof example of how look.

(also, given rest of requirements, may want @ making type parameter <t extends satellite>, or whatever base satellite interface is.)


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

.htaccess - Matching full URL in RewriteCond -