List of usage examples for java.lang.reflect Array newInstance
public static Object newInstance(Class<?> componentType, int... dimensions) throws IllegalArgumentException, NegativeArraySizeException
From source file:net.sf.qooxdoo.rpc.RemoteCallUtils.java
/** * Converts JSON types to "normal" java types. * * @param obj the object to convert (must not be * <code>null</code>, but can be * <code>JSONObject.NULL</code>). * @param targetType the desired target type (must not be * <code>null</code>). * * @return the converted object./* w ww.jav a 2 s.c o m*/ * * @exception IllegalArgumentException thrown if the desired * conversion is not possible. */ public Object toJava(Object obj, Class targetType) { try { if (obj == JSONObject.NULL) { if (targetType == Integer.TYPE || targetType == Double.TYPE || targetType == Boolean.TYPE || targetType == Long.TYPE || targetType == Float.TYPE) { // null does not work for primitive types throw new Exception(); } return null; } if (obj instanceof JSONArray) { Class componentType; if (targetType == null || targetType == Object.class) { componentType = null; } else { componentType = targetType.getComponentType(); } JSONArray jsonArray = (JSONArray) obj; int length = jsonArray.length(); Object retVal = Array.newInstance((componentType == null ? Object.class : componentType), length); for (int i = 0; i < length; ++i) { Array.set(retVal, i, toJava(jsonArray.get(i), componentType)); } return retVal; } if (obj instanceof JSONObject) { JSONObject jsonObject = (JSONObject) obj; JSONArray names = jsonObject.names(); if (targetType == Map.class || targetType == HashMap.class || targetType == null || targetType == Object.class) { HashMap retVal = new HashMap(); if (names != null) { int length = names.length(); String name; for (int i = 0; i < length; ++i) { name = names.getString(i); retVal.put(name, toJava(jsonObject.get(name), null)); } } return retVal; } Object bean; String requestedTypeName = jsonObject.optString("class", null); if (requestedTypeName != null) { Class clazz = resolveClassHint(requestedTypeName, targetType); if (clazz == null || !targetType.isAssignableFrom(clazz)) { throw new Exception(); } bean = clazz.newInstance(); // TODO: support constructor parameters } else { bean = targetType.newInstance(); } if (names != null) { int length = names.length(); String name; PropertyDescriptor desc; for (int i = 0; i < length; ++i) { name = names.getString(i); if (!"class".equals(name)) { desc = PropertyUtils.getPropertyDescriptor(bean, name); if (desc != null && desc.getWriteMethod() != null) { PropertyUtils.setSimpleProperty(bean, name, toJava(jsonObject.get(name), desc.getPropertyType())); } } } } return bean; } if (targetType == null || targetType == Object.class) { return obj; } Class actualTargetType; Class sourceType = obj.getClass(); if (targetType == Integer.TYPE) { actualTargetType = Integer.class; } else if (targetType == Boolean.TYPE) { actualTargetType = Boolean.class; } else if ((targetType == Double.TYPE || targetType == Double.class) && Number.class.isAssignableFrom(sourceType)) { return new Double(((Number) obj).doubleValue()); // TODO: maybe return obj directly if it's a Double } else if ((targetType == Float.TYPE || targetType == Float.class) && Number.class.isAssignableFrom(sourceType)) { return new Float(((Number) obj).floatValue()); } else if ((targetType == Long.TYPE || targetType == Long.class) && Number.class.isAssignableFrom(sourceType)) { return new Long(((Number) obj).longValue()); } else { actualTargetType = targetType; } if (!actualTargetType.isAssignableFrom(sourceType)) { throw new Exception(); } return obj; } catch (IllegalArgumentException e) { throw e; } catch (Exception e) { throw new IllegalArgumentException("Cannot convert " + (obj == null ? null : obj.getClass().getName()) + " to " + (targetType == null ? null : targetType.getName())); } }
From source file:ArrayMap.java
/** * Inserts an element into the array// w w w . j a va2 s .c om * * @param <T> * The type of the object array * @param anArray * The array to insert into * @param anElement * The element to insert * @param anIndex * The index for the new element * @return The new array with all elements of <code>anArray</code>, but with * <code>anElement</code> inserted at index <code>anIndex</code> */ public static <T> T[] add(T[] anArray, T anElement, int anIndex) { T[] ret; if (anArray == null) { if (anIndex != 0) throw new ArrayIndexOutOfBoundsException("Cannot set " + anIndex + " element in a null array"); ret = (T[]) Array.newInstance(anElement.getClass(), 1); ret[0] = anElement; return ret; } else ret = (T[]) Array.newInstance(anArray.getClass().getComponentType(), anArray.length + 1); System.arraycopy(anArray, 0, ret, 0, anIndex); put(ret, anElement, anIndex); System.arraycopy(anArray, anIndex, ret, anIndex + 1, anArray.length - anIndex); return ret; }
From source file:net.navasoft.madcoin.backend.services.rest.impl.Provider.java
/** * Sets the policies./*from w ww . j a v a2s. c o m*/ * * @param policies * the new policies * @since 8/09/2014, 01:45:38 AM */ @Override public void setPolicies(Object... policies) { if (policies.length > 2) { inicioVentanas = (Calendar[]) Array.newInstance(Calendar.class, (policies.length - 2) / 2); finVentanas = (Calendar[]) Array.newInstance(Calendar.class, (policies.length - 2) / 2); Arrays.fill(inicioVentanas, Calendar.getInstance()); Arrays.fill(finVentanas, Calendar.getInstance()); } providerPreferrence = (ScopeProvider) policies[policies.length - 2]; providerContact = (String) policies[policies.length - 1]; policies = ArrayUtils.remove(policies, policies.length - 2); policies = ArrayUtils.remove(policies, policies.length - 1); int ini = 0; int fini = 0; for (int contadorMultiplos = 0; contadorMultiplos < policies.length; contadorMultiplos++) { if (contadorMultiplos % 2 == 0) { java.util.Date horario = (Date) policies[contadorMultiplos]; inicioVentanas[ini].setTime(horario); ini++; } else { java.util.Date horario = (Date) policies[contadorMultiplos]; finVentanas[fini].setTime(horario); fini++; } } }
From source file:net.drgnome.virtualpack.util.Util.java
public static <T> T[] createGenericArray(Class<T> clazz, int... size) { for (int i = 0; i < size.length; i++) { if (size[i] < 0) { size[i] = 0;//from www. j a va 2s .c o m } } try { return (T[]) (Array.newInstance(clazz, size)); } catch (Exception e) { e.printStackTrace(); return (T[]) null; } }
From source file:edu.umn.cs.spatialHadoop.operations.ConvexHull.java
/** * Computes the convex hull of a set of points using a divide and conquer * in-memory algorithm. This function implements Andrew's modification to * the Graham scan algorithm.//w ww . j a va 2 s. com * * @param points * @return */ public static <P extends Point> P[] convexHullInMemory(P[] points) { Stack<P> s1 = new Stack<P>(); Stack<P> s2 = new Stack<P>(); Arrays.sort(points); // Lower chain for (int i = 0; i < points.length; i++) { while (s1.size() > 1) { P p1 = s1.get(s1.size() - 2); P p2 = s1.get(s1.size() - 1); P p3 = points[i]; double crossProduct = (p2.x - p1.x) * (p3.y - p1.y) - (p2.y - p1.y) * (p3.x - p1.x); if (crossProduct <= 0) s1.pop(); else break; } s1.push(points[i]); } // Upper chain for (int i = points.length - 1; i >= 0; i--) { while (s2.size() > 1) { P p1 = s2.get(s2.size() - 2); P p2 = s2.get(s2.size() - 1); P p3 = points[i]; double crossProduct = (p2.x - p1.x) * (p3.y - p1.y) - (p2.y - p1.y) * (p3.x - p1.x); if (crossProduct <= 0) s2.pop(); else break; } s2.push(points[i]); } s1.pop(); s2.pop(); s1.addAll(s2); return s1.toArray((P[]) Array.newInstance(s1.firstElement().getClass(), s1.size())); }
From source file:name.abhijitsarkar.algorithms.core.Sorter.java
private static int[][] scatter(int[] arr) { @SuppressWarnings("unchecked") List<Integer>[] tempBuckets = (List<Integer>[]) Array.newInstance(ArrayList.class, 8); long hash = -1; int idx = -1; List<Integer> bucket = null; for (int i : arr) { hash = DJBHash(Integer.valueOf(i).toString()); idx = computeIndex(hash);//w w w . ja va 2 s .c o m bucket = createOrGetBucket(tempBuckets, idx); bucket.add(i); } return toArray(tempBuckets); }
From source file:ArrayUtil.java
/** * Returns a copy of the old array {@code oldArray} but with the element at the * give index {@code idx} removed.//w w w . j av a 2 s . co m * * @throws {@link IllegalArgumentException} if the array index is out of bounds. */ @SuppressWarnings("unchecked") public static <T> T[] remove(T[] oldArray, int idx) { if (idx < 0 || idx >= oldArray.length) throw new IllegalArgumentException("array index " + idx + " out of bounds"); Class<?> component = oldArray.getClass().getComponentType(); T[] array = (T[]) Array.newInstance(component, oldArray.length - 1); if (idx == 0) System.arraycopy(oldArray, 1, array, 0, array.length); else { System.arraycopy(oldArray, 0, array, 0, idx); System.arraycopy(oldArray, idx + 1, array, idx, array.length - idx); } return array; }
From source file:at.alladin.rmbt.shared.hstoreparser.Hstore.java
/** * //w w w . j a v a 2s . c o m * @param json * @param clazz * @return * @throws HstoreParseException */ @SuppressWarnings("unchecked") public <T> T[] fromJSONArray(JSONArray json, Class<T> clazz) throws HstoreParseException { HstoreParser<?> parser = parserMap.get(clazz); T[] array = (T[]) Array.newInstance(clazz, json.length()); try { if (parser != null) { for (int i = 0; i < json.length(); i++) { array[i] = ((T) parser.fromJson(json.getJSONObject(i))); } return array; } } catch (JSONException e) { throw new HstoreParseException(HstoreParseException.HSTORE_FORMAT_UNSUPPORTED + json, e); } return null; }
From source file:cn.wanghaomiao.seimi.utils.GenericUtils.java
/** * ?, , : Generic ???//w ww. jav a 2s . co m * * @param genericType - Generic ? * @return ? */ public static Class<?>[] getActualClass(Type genericType) { if (genericType instanceof ParameterizedType) { Type[] actualTypes = ((ParameterizedType) genericType).getActualTypeArguments(); Class<?>[] actualClasses = new Class<?>[actualTypes.length]; int i = 0; while (i < actualTypes.length) { Type actualType = actualTypes[i]; if (actualType instanceof Class<?>) { actualClasses[i] = (Class<?>) actualType; } else if (actualType instanceof GenericArrayType) { Type componentType = ((GenericArrayType) actualType).getGenericComponentType(); actualClasses[i] = Array.newInstance((Class<?>) componentType, 0).getClass(); } i++; } return actualClasses; } return EMPTY_CLASSES; }
From source file:de.alpharogroup.lang.ObjectExtensions.java
/** * Try to clone the given object./* ww w . j av a2s . c o m*/ * * @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; }