Android examples for java.lang:Class
Create object instance from String and Class<?>
import java.lang.reflect.InvocationTargetException; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; public class Main{ public static Object fromString(String str, Class<?> clazz) throws Exception { Object o = null;/*from www . j a v a 2s .c om*/ if (clazz.equals(String.class)) { o = str; } else if (clazz.equals(Integer.TYPE) || clazz.equals(Integer.class)) { o = Integer.parseInt(str); } else if (clazz.equals(Long.TYPE) || clazz.equals(Long.class)) { o = Long.parseLong(str); } else if (clazz.equals(Float.TYPE) || clazz.equals(Float.class)) { o = Float.parseFloat(str); } else if (clazz.equals(Double.TYPE) || clazz.equals(Double.class)) { o = Double.parseDouble(str); } else if (clazz.equals(Boolean.TYPE) || clazz.equals(Boolean.class)) { o = Boolean.parseBoolean(str); } else if (clazz.equals(Date.class)) { o = DATE_FORMAT.parse(str); } else if (clazz.equals(Byte.TYPE) || clazz.equals(Byte.class)) { o = Byte.parseByte(str); } else if (clazz.equals(Short.TYPE) || clazz.equals(Short.class)) { o = Short.parseShort(str); } else { o = clazz.getConstructor(String.class).newInstance(str); } return o; } }