2013-12-12 119 views
1

我该如何减少这一点在java中用于Android的反射几行?使用反射来投射一个对象在java中为Android

_properties是ContentValues对象和是一个对象)

if (value instanceof String) 
    { 
     this._properties.put( key, value.toString()); 
    } else if (value instanceof Long) { 
     this._properties.put( key, Long.valueOf(value.toString())); 
    } else if (value instanceof Integer) { 
     this._properties.put( key, Integer.valueOf(value.toString())); 
    } else if (value instanceof Boolean) { 
     this._properties.put( key, Boolean.valueOf(value.toString())); 
    } else if (value instanceof Byte) { 
     this._properties.put( key, Byte.valueOf(value.toString())); 
    } else ... 
+0

我不是Android开发人员,所以我为我的无知感到抱歉,但为什么你甚至检查'value'类型? 'this._properties.put(key,value)是否有问题;'? – Pshemo

+2

@Pshemo'ContentValues'没有一个通用的'put object'方法,只有某些类型的类型化方法(因为内部序列化/ parcel):http://developer.android.com/reference/android/content/ContentValues .html当使用这些时,最好是转换而不是转换为一个字符串,但这会减少只需稍微使用的代码(例如'this._properties.put(key,(Byte)value)')。 –

+0

'this._properties.put(key,(Byte)value))'与this._properties.put(key,Byte.valueOf(value.toString()))'是一样的,对吧? – spacebiker

回答

2

无反射需要:

_properties.put(key, value.toString()); 

不幸的是ContentValues没有put(String, Object)即使在内部的值是存储在HashMap<String, Object>

为什么存储值String作品是所有ContentValuesgetAsFoo()存取支持从String转换为Foo

+0

所以你的意思是我可以使用value.toString()来存储该值,并在以后继续使用instanceOf ..? '(_properties instanceOf [whatever_type_here])' – spacebiker

+0

这些值将被存储为'String's,因此如果使用通用的get():Object'来访问类型信息,则会丢失类型信息。但'getAs ...()'访问器会尝试在放弃之前将'String'转换为请求的类型。 – laalto

+1

尽管这是一种可行的方法,但它与原始代码不同,因为您会丢失该类型。对于无法无损序列化为字符串的类型,在反序列化('Float','Double')之后,该值可能会稍有不同。在大多数情况下,这些问题是微不足道的 - 你不会处理任意数据,所以你知道与某些键相关的类型,我猜从现在开始,没有太多的应用需要完全精确的(除了初学者代码比较用== ==浮点值)。另一方面,您只需写一次原始代码(通过投射)。 –