Created
March 30, 2015 09:29
-
-
Save Nilzor/f0eb9c44d767f70a4449 to your computer and use it in GitHub Desktop.
Java langUtils. Some HashMap and reflection stuff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class LangUtils { | |
public static <K,V> ArrayList<V> getOrCreateArrayList(HashMap<K, ArrayList<V>> hashMap, K key) { | |
ArrayList<V> list = hashMap.get(key); | |
if (list == null) { | |
list = new ArrayList<V>(); | |
hashMap.put(key, list); | |
} | |
return list; | |
} | |
public static Object toPrimitive( Class clazz, String value ) { | |
if( Boolean.class == clazz ) return Boolean.parseBoolean( value ); | |
if( boolean.class == clazz ) return Boolean.parseBoolean( value ); | |
if( Byte.class == clazz ) return Byte.parseByte( value ); | |
if( byte.class == clazz ) return Byte.parseByte( value ); | |
if( Short.class == clazz ) return Short.parseShort( value ); | |
if( short.class == clazz ) return Short.parseShort( value ); | |
if( Integer.class == clazz ) return Integer.parseInt(value); | |
if (int.class == clazz) return Integer.parseInt(value); | |
if( Long.class == clazz ) return Long.parseLong( value ); | |
if( long.class == clazz ) return Long.parseLong( value ); | |
if( Float.class == clazz ) return Float.parseFloat( value ); | |
if( float.class == clazz ) return Long.parseLong( value ); | |
if( Double.class == clazz ) return Double.parseDouble( value ); | |
if( double.class == clazz ) return Long.parseLong( value ); | |
return value; | |
} | |
public static boolean tryAssign(Object target, String primitiveFieldName, String value) { | |
try { | |
Field field = target.getClass().getField(primitiveFieldName); | |
Object parsedValue = toPrimitive(field.getType(), value); | |
field.set(target, parsedValue); | |
return true; | |
} catch (Exception ex) { | |
System.out.println(ExceptionHelper.ExceptionToString(ex)); | |
Log.d("", ExceptionHelper.ExceptionToString(ex)); | |
return false; | |
} | |
} | |
/** Converts a hashMap to an arraylist by specifiying a join string to glue the | |
* key and value together. | |
* Example: Key=IsEnabled, Value=True. Call with joinChar '=' and you get: | |
* { "Key=True" } */ | |
public static <T,U> ArrayList<String> joinKeyValues(HashMap<T, U> dic, String joinChar) { | |
Set<T> keys = dic.keySet(); | |
ArrayList<String> retVal = new ArrayList<>(dic.size()); | |
for (Object key : keys) { | |
Object val = dic.get(key); | |
String s = key + joinChar + val; | |
retVal.add(s); | |
} | |
return retVal; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment