java - Transform one type to another -


i need improve code:

final string valuestring = value.tostring();  if (path.class.isassignablefrom(destinationtype)) {   fixedvalues.put(key, paths.get(valuestring)); } /* ... above, other types ... */ { } else {   fixedvalues.put(key, valuestring); } 

so decided implement transformer-like converts type x y.

i created interface

public interface converter<s, d> {   d convert(final s source);    class<d> getdestinationclass();   class<s> getsourceclass(); } 

so when need implement conversion implement interface

public class stringtointegerconverter implements converter<string, integer> {   @override   public integer convert(final string source) {     return integer.parseint(source);   }    @override   public class<integer> getdestinationclass() {     return integer.class;   }    @override   public class<string> getsourceclass() {     return string.class;   } } 

(example of string -> integer)

now, convert types have class converters contains inside table (guava table 2 keys) converters stored.

private final static immutabletable<class<?>, class<?>, converter<?, ?>> converters; 

and has method convert

public <s, d> d convert(final class<s> source, final class<d> destination, final s value) {     return destination.cast(converters.get(source, destination).convert(source.cast(value))); } 

the error is

incompatible types: s cannot converted capture#1 of ? 

at source.cast(value)

because store them in map ? i'm stuck. don't know how can fix this. got feeling it's not possible, i'm posting see if i'm wrong.

i read this spring, it's different way

what trying achieve possible:

@suppresswarnings("unchecked") public <s, d> d convert(final class<s> source, final class<d> destination, final s value) {     final converter<s, d> converter = (converter) converters.get(source, destination);      return destination.cast(converter.convert(source.cast(value))); } 

however, code nature cannot guarantee type safety. have guarantee, 3 elements put table compatible.


Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -