List of usage examples for java.lang.reflect Array set
public static native void set(Object array, int index, Object value) throws IllegalArgumentException, ArrayIndexOutOfBoundsException;
From source file:com.laxser.blitz.lama.provider.jdbc.PreparedStatementCallbackReturnId.java
@Override public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException { if (setter != null) { setter.setValues(ps);//from w w w. ja v a 2 s. co m } int updated = ps.executeUpdate(); if (updated == 0) { if (returnType.isArray()) { return Array.newInstance(wrappedIdType, 0); } else { return defaultValueOf(wrappedIdType); } } ResultSet keys = ps.getGeneratedKeys(); if (keys != null) { try { Object ret = null; if (returnType.isArray()) { keys.last(); int length = keys.getRow(); keys.beforeFirst(); ret = Array.newInstance(wrappedIdType, length); } for (int i = 0; keys.next(); i++) { Object value = mapper.mapRow(keys, i); if (value == null && idType.isPrimitive()) { // ?primitive??null?? value = defaultValueOf(wrappedIdType); } if (ret != null) { Array.set(ret, i + 1, value); } else { ret = value; break; } } return ret; } finally { JdbcUtils.closeResultSet(keys); } } else { if (returnType.isArray()) { return Array.newInstance(wrappedIdType, 0); } else { return defaultValueOf(wrappedIdType); } } }
From source file:de.alpharogroup.lang.ObjectExtensions.java
/** * Try to clone the given object.//from w ww . j a v a 2 s . c om * * @param object * The object to clone. * @return The cloned object or null if the clone process failed. * @throws NoSuchMethodException * the no such method exception * @throws SecurityException * Thrown if the security manager indicates a security violation. * @throws IllegalAccessException * the illegal access exception * @throws IllegalArgumentException * the illegal argument exception * @throws InvocationTargetException * the invocation target exception * @throws ClassNotFoundException * the class not found exception * @throws InstantiationException * the instantiation exception * @throws IOException * Signals that an I/O exception has occurred. */ public static Object cloneObject(final Object object) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException, InstantiationException, IOException { Object clone = null; // Try to clone the object if it implements Serializable. if (object instanceof Serializable) { clone = SerializedObjectUtils.copySerializedObject((Serializable) object); if (clone != null) { return clone; } } // Try to clone the object if it is Cloneble. if (clone == null && object instanceof Cloneable) { if (object.getClass().isArray()) { final Class<?> componentType = object.getClass().getComponentType(); if (componentType.isPrimitive()) { int length = Array.getLength(object); clone = Array.newInstance(componentType, length); while (length-- > 0) { Array.set(clone, length, Array.get(object, length)); } } else { clone = ((Object[]) object).clone(); } if (clone != null) { return clone; } } final Class<?> clazz = object.getClass(); final Method cloneMethod = clazz.getMethod("clone", (Class[]) null); clone = cloneMethod.invoke(object, (Object[]) null); if (clone != null) { return clone; } } // Try to clone the object by copying all his properties with // the BeanUtils.copyProperties() method. if (clone == null) { clone = ReflectionUtils.getNewInstance(object); BeanUtils.copyProperties(clone, object); } return clone; }
From source file:org.dhatim.javabean.BeanUtils.java
/** * Convert the supplied List into an array of the specified array type. * @param list The List instance to be converted. * @param arrayClass The array type./*from w w w . j ava 2 s. c o m*/ * @return The array. */ public static Object convertListToArray(List<?> list, Class<?> arrayClass) { AssertArgument.isNotNull(list, "list"); AssertArgument.isNotNull(arrayClass, "arrayClass"); int length = list.size(); Object arrayObj = Array.newInstance(arrayClass, list.size()); for (int i = 0; i < length; i++) { try { Array.set(arrayObj, i, list.get(i)); } catch (ClassCastException e) { logger.error("Failed to cast type '" + list.get(i).getClass().getName() + "' to '" + arrayClass.getName() + "'.", e); } } return arrayObj; }
From source file:Main.java
/** * convert value to given type./*from ww w .j av a2 s . c o m*/ * null safe. * * @param value value for convert * @param type will converted type * @return value while converted */ public static Object convertCompatibleType(Object value, Class<?> type) { if (value == null || type == null || type.isAssignableFrom(value.getClass())) { return value; } if (value instanceof String) { String string = (String) value; if (char.class.equals(type) || Character.class.equals(type)) { if (string.length() != 1) { throw new IllegalArgumentException(String.format("CAN NOT convert String(%s) to char!" + " when convert String to char, the String MUST only 1 char.", string)); } return string.charAt(0); } else if (type.isEnum()) { return Enum.valueOf((Class<Enum>) type, string); } else if (type == BigInteger.class) { return new BigInteger(string); } else if (type == BigDecimal.class) { return new BigDecimal(string); } else if (type == Short.class || type == short.class) { return Short.valueOf(string); } else if (type == Integer.class || type == int.class) { return Integer.valueOf(string); } else if (type == Long.class || type == long.class) { return Long.valueOf(string); } else if (type == Double.class || type == double.class) { return Double.valueOf(string); } else if (type == Float.class || type == float.class) { return Float.valueOf(string); } else if (type == Byte.class || type == byte.class) { return Byte.valueOf(string); } else if (type == Boolean.class || type == boolean.class) { return Boolean.valueOf(string); } else if (type == Date.class) { try { return new SimpleDateFormat(DATE_FORMAT).parse((String) value); } catch (ParseException e) { throw new IllegalStateException("Failed to parse date " + value + " by format " + DATE_FORMAT + ", cause: " + e.getMessage(), e); } } else if (type == Class.class) { return forName((String) value); } } else if (value instanceof Number) { Number number = (Number) value; if (type == byte.class || type == Byte.class) { return number.byteValue(); } else if (type == short.class || type == Short.class) { return number.shortValue(); } else if (type == int.class || type == Integer.class) { return number.intValue(); } else if (type == long.class || type == Long.class) { return number.longValue(); } else if (type == float.class || type == Float.class) { return number.floatValue(); } else if (type == double.class || type == Double.class) { return number.doubleValue(); } else if (type == BigInteger.class) { return BigInteger.valueOf(number.longValue()); } else if (type == BigDecimal.class) { return BigDecimal.valueOf(number.doubleValue()); } else if (type == Date.class) { return new Date(number.longValue()); } } else if (value instanceof Collection) { Collection collection = (Collection) value; if (type.isArray()) { int length = collection.size(); Object array = Array.newInstance(type.getComponentType(), length); int i = 0; for (Object item : collection) { Array.set(array, i++, item); } return array; } else if (!type.isInterface()) { try { Collection result = (Collection) type.newInstance(); result.addAll(collection); return result; } catch (Throwable e) { e.printStackTrace(); } } else if (type == List.class) { return new ArrayList<>(collection); } else if (type == Set.class) { return new HashSet<>(collection); } } else if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) { Collection collection; if (!type.isInterface()) { try { collection = (Collection) type.newInstance(); } catch (Throwable e) { collection = new ArrayList<>(); } } else if (type == Set.class) { collection = new HashSet<>(); } else { collection = new ArrayList<>(); } int length = Array.getLength(value); for (int i = 0; i < length; i++) { collection.add(Array.get(value, i)); } return collection; } return value; }
From source file:org.jolokia.converter.json.ArrayExtractor.java
/** * Set a value in an array//from www . j a va2 s.c o m * * @param pConverter the global converter in order to be able do dispatch for * serializing inner data types * @param pInner object on which to set the value (which must be a {@link List}) * @param pIndex index (as string) where to set the value within the array * @param pValue the new value to set * @return the old value at this index * @throws IllegalAccessException * @throws InvocationTargetException */ public Object setObjectValue(StringToObjectConverter pConverter, Object pInner, String pIndex, Object pValue) throws IllegalAccessException, InvocationTargetException { Class clazz = pInner.getClass(); if (!clazz.isArray()) { throw new IllegalArgumentException("Not an array to set a value, but " + clazz + ". (index = " + pIndex + ", value = " + pValue + ")"); } int idx; try { idx = Integer.parseInt(pIndex); } catch (NumberFormatException exp) { throw new IllegalArgumentException("Non-numeric index for accessing array " + pInner + ". (index = " + pIndex + ", value to set = " + pValue + ")", exp); } Class type = clazz.getComponentType(); Object value = pConverter.prepareValue(type.getName(), pValue); Object oldValue = Array.get(pInner, idx); Array.set(pInner, idx, value); return oldValue; }
From source file:net.buffalo.protocal.util.ClassUtil.java
public static Object convertValue(Object value, Class targetType) { if (value.getClass().equals(targetType)) return value; if (targetType.isPrimitive()) { targetType = getWrapperClass(targetType); }/*from ww w .j av a2 s. co m*/ if (targetType.isAssignableFrom(value.getClass())) return value; if ((value instanceof String || value instanceof Number) && Number.class.isAssignableFrom(targetType)) { try { Constructor ctor = targetType.getConstructor(new Class[] { String.class }); return ctor.newInstance(new Object[] { value.toString() }); } catch (Exception e) { LOGGER.error("convert type error", e); throw new RuntimeException( "Cannot convert from " + value.getClass().getName() + " to " + targetType, e); } } if (targetType.isArray() && Collection.class.isAssignableFrom(value.getClass())) { Collection collection = (Collection) value; Object array = Array.newInstance(targetType.getComponentType(), collection.size()); int i = 0; for (Iterator iter = collection.iterator(); iter.hasNext();) { Object val = iter.next(); Array.set(array, i++, val); } return array; } if (Collection.class.isAssignableFrom(targetType) && value.getClass().isArray()) { return Arrays.asList((Object[]) value); } throw new IllegalArgumentException( "Cannot convert from " + value.getClass().getName() + " to " + targetType); }
From source file:com.adobe.acs.commons.mcp.util.AnnotatedFieldDeserializer.java
private static void parseInputList(Object target, String[] values, Field field) throws ReflectiveOperationException, ParseException { List convertedValues = new ArrayList(); Class type = getCollectionComponentType(field); for (String value : values) { Object val = convertValue(value, type); convertedValues.add(val); }/* w w w. java 2 s. com*/ if (field.getType().isArray()) { Object array = Array.newInstance(field.getType().getComponentType(), convertedValues.size()); for (int i = 0; i < convertedValues.size(); i++) { Array.set(array, i, convertedValues.get(i)); } FieldUtils.writeField(field, target, array, true); } else { Collection c = (Collection) getInstantiatableListType(field.getType()).newInstance(); c.addAll(convertedValues); FieldUtils.writeField(field, target, c, true); } }
From source file:org.protempa.backend.BackendInstanceSpec.java
public Object getProperty(String name) throws InvalidPropertyNameException { BackendPropertySpec get = this.propertyMap.get(name); if (get == null) { throw new InvalidPropertyNameException(name); } else {//w ww .java 2 s .c o m Object value = this.properties.get(name); if (value != null && value instanceof List) { List<?> l = (List<?>) value; Object result = Array.newInstance(get.getType().getCls().getComponentType(), l.size()); for (int i = 0, n = l.size(); i < n; i++) { Array.set(result, i, l.get(i)); } return result; } else { return this.properties.get(name); } } }
From source file:ome.util.ModelMapper.java
/** * known immutables are return unchanged. * // w ww. ja v a 2s. c o m * @param current * @return a possibly uninitialized object which will be finalized as the * object graph is walked. */ public Object findTarget(Object current) { // IMMUTABLES if (null == current || current instanceof Number || current instanceof String || current instanceof Boolean || current instanceof Timestamp || current instanceof Class) { return current; } Object target = model2target.get(current); if (null == target) { Class currentType = current.getClass(); Class targetType = null; if (currentType.isArray()) { Class componentType = null; try { int length = Array.getLength(current); componentType = currentType.getComponentType(); target = Array.newInstance(componentType, length); for (int i = 0; i < length; i++) { Object currentValue = Array.get(current, i); Object targetValue = this.filter("ARRAY", currentValue); Array.set(target, i, targetValue); } } catch (Exception e) { log.error("Error creating new array of type " + componentType, e); throwOnNewInstanceException(current, componentType, e); } } else { targetType = findClass(currentType); if (null == targetType) { throw new InternalException("Cannot handle type:" + current); } try { target = targetType.newInstance(); } catch (Exception e) { log.error("Error creating new instance of target type" + current, e); throwOnNewInstanceException(current, targetType, e); } } model2target.put(current, target); } return target; }
From source file:com.nfwork.dbfound.json.converter.NumberArrayConverter.java
protected int[] createDimensions(int length, int initial) { Object dims = Array.newInstance(int.class, length); Array.set(dims, 0, new Integer(initial)); return (int[]) dims; }