2013-12-12 5 views
1

어떻게 이것을 Android에서 Java로 리플렉션을 사용하여 몇 줄로 줄일 수 있습니까? 리플렉션을 사용하여 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

나는 안드로이드 개발자가 아니기 때문에 미안하지만, 왜 'value'타입을 체크하고 있는가? 'this._properties.put (key, value);에 문제가 있습니까? – Pshemo

+2

@Pshemo'ContentValues'는 일반적인'put 객체'메소드를 가지고 있지 않습니다. 내부 직렬화/소팅 때문에 특정 유형에 대한 타입이 지정된 메소드 만 있습니다 : 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

그래서 가치를 저장하고 여전히 instanceOf를 나중에 사용하기 위해 value.toString()을 사용할 수 있다는 것을 의미합니까? '(_properties instanceOf [whatever_type_here])' – spacebiker

+0

값들은'String's로 저장 될 것이므로 접근하기 위해 일반'get() : Object'를 사용하면 타입 정보가 손실됩니다. 그러나 getAs ...() 접근자는'String'을 요청 된 타입으로 변환하려고 시도 할 것입니다. – laalto

+1

이것은 실행 가능한 방법이지만 유형을 잃어 버리면 원래 코드와 다릅니다. 손실없이 문자열에 직렬화 할 수없는 유형의 경우 직렬화 해제 후에 값이 약간 다를 수 있습니다 ('Float','Double'). 대부분의 경우 이러한 문제는 중요하지 않습니다. 임의의 데이터를 처리하지 않아 특정 키와 관련된 유형을 알 수 없으므로 전체 정밀도가 필요한 응용 프로그램이 많지 않습니다 (비교할 수있는 초보자 코드 제외). 부동 소수점 값은'=='). 반면에 한 번만 원래 코드를 (캐스팅과 함께) 작성합니다. –

관련 문제