Java Code Examples for java.lang.reflect.Array

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project activemq-apollo, under directory /apollo-util/src/main/scala/org/apache/activemq/apollo/util/.

Source file: IntrospectionSupport.java

  29 
vote

private static Object convert(Object value,Class<?> type){
  if (type.isArray()) {
    if (value.getClass().isArray()) {
      int length=Array.getLength(value);
      Class<?> componentType=type.getComponentType();
      Object rc=Array.newInstance(componentType,length);
      for (int i=0; i < length; i++) {
        Object o=Array.get(value,i);
        Array.set(rc,i,convert(o,componentType));
      }
      return rc;
    }
  }
  PropertyEditor editor=PropertyEditorManager.findEditor(type);
  if (editor != null) {
    editor.setAsText(value.toString());
    return editor.getValue();
  }
  return null;
}
 

Example 2

From project activiti-webapp-rest-generic, under directory /activiti-webapp-rest/src/main/java/org/activiti/rest/builder/management/.

Source file: TableDataObjectBuilder.java

  29 
vote

protected void putColumnValue(JSONObject json,String key,Object value) throws JSONException {
  if (value == null) {
    JSONUtil.putRetainNull(json,key,null);
  }
 else   if (value instanceof List<?>) {
    json.put(key,((List<?>)value).size());
  }
 else   if (value.getClass().isArray()) {
    json.put(key,Array.getLength(value));
  }
 else   if (value instanceof Date) {
    String date=JSONUtil.formatISO8601Date((Date)value);
    JSONUtil.putRetainNull(json,key,date);
  }
 else {
    JSONUtil.putRetainNull(json,key,value);
  }
}
 

Example 3

From project AdminCmd, under directory /src/main/java/be/Balor/Tools/.

Source file: Utils.java

  29 
vote

@SuppressWarnings("unchecked") public static <T>T[] Arrays_copyOfRange(final T[] original,final int start,final int end){
  if (original.length >= start && 0 <= start) {
    if (start <= end) {
      final int length=end - start;
      final int copyLength=Math.min(length,original.length - start);
      final T[] copy=(T[])Array.newInstance(original.getClass().getComponentType(),length);
      System.arraycopy(original,start,copy,0,copyLength);
      return copy;
    }
    throw new IllegalArgumentException();
  }
  throw new ArrayIndexOutOfBoundsException();
}
 

Example 4

From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/net/poolable/copy/.

Source file: CursorableLinkedList.java

  29 
vote

/** 
 * Returns an array containing all of the elements in this list in proper sequence; the runtime type of the returned array is that of the specified array. Obeys the general contract of the {@link Collection#toArray()} method.
 * @param a      the array into which the elements of this list are tobe stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.
 * @return an array containing the elements of this list.
 * @exception ArrayStoreException if the runtime type of the specified array is not a supertype of the runtime type of every element in this list.
 */
public Object[] toArray(Object a[]){
  if (a.length < _size) {
    a=(Object[])Array.newInstance(a.getClass().getComponentType(),_size);
  }
  int i=0;
  for (Listable elt=_head.next(), past=null; null != elt && past != _head.prev(); elt=(past=elt).next()) {
    a[i++]=elt.value();
  }
  if (a.length > _size) {
    a[_size]=null;
  }
  return a;
}
 

Example 5

From project amplafi-sworddance, under directory /src/main/java/com/sworddance/util/.

Source file: CUtilities.java

  29 
vote

/** 
 * size of object
 * @param object {@link Map},  {@link Collection}, Array,  {@link CharSequence}
 * @return 0 if null
 */
@SuppressWarnings("unchecked") public static int size(Object object){
  int total=0;
  if (object != null) {
    if (object instanceof Map) {
      total=((Map)object).size();
    }
 else     if (object instanceof Collection) {
      total=((Collection)object).size();
    }
 else     if (object.getClass().isArray()) {
      total=Array.getLength(object);
    }
 else     if (object instanceof CharSequence) {
      total=((CharSequence)object).length();
    }
 else     if (object instanceof Iterable) {
      Iterator it=((Iterable)object).iterator();
      while (it.hasNext()) {
        total++;
        it.next();
      }
    }
 else {
      throw new ApplicationIllegalArgumentException("Unsupported object type: " + object.getClass().getName());
    }
  }
  return total;
}
 

Example 6

From project and-bible, under directory /AndBible/src/org/apache/commons/lang/.

Source file: ArrayUtils.java

  29 
vote

/** 
 * <p>Produces a new array containing the elements between the start and end indices.</p> <p>The start index is inclusive, the end index exclusive. Null array input produces null output.</p> <p>The component type of the subarray is always the same as that of the input array. Thus, if the input is an array of type <code>Date</code>, the following usage is envisaged:</p> <pre> Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5); </pre>
 * @param array  the array
 * @param startIndexInclusive  the starting index. Undervalue (&lt;0)is promoted to 0, overvalue (&gt;array.length) results in an empty array.
 * @param endIndexExclusive  elements up to endIndex-1 are present in thereturned subarray. Undervalue (&lt; startIndex) produces empty array, overvalue (&gt;array.length) is demoted to array length.
 * @return a new array containing the elements betweenthe start and end indices.
 * @since 2.1
 */
public static <T>T[] subarray(T[] array,int startIndexInclusive,int endIndexExclusive){
  if (array == null) {
    return null;
  }
  if (startIndexInclusive < 0) {
    startIndexInclusive=0;
  }
  if (endIndexExclusive > array.length) {
    endIndexExclusive=array.length;
  }
  int newSize=endIndexExclusive - startIndexInclusive;
  Class<?> type=array.getClass().getComponentType();
  if (newSize <= 0) {
    @SuppressWarnings("unchecked") final T[] emptyArray=(T[])Array.newInstance(type,0);
    return emptyArray;
  }
  @SuppressWarnings("unchecked") T[] subarray=(T[])Array.newInstance(type,newSize);
  System.arraycopy(array,startIndexInclusive,subarray,0,newSize);
  return subarray;
}
 

Example 7

From project Android_1, under directory /org.eclipse.ecf.android/src/org/eclipse/ecf/android/.

Source file: RemoteServiceRegistrationImpl.java

  29 
vote

/** 
 * Attempt to clone the value if necessary and possible. For some strange reason, you can test to see of an Object is Cloneable but you can't call the clone method since it is protected on Object!
 * @param value object to be cloned.
 * @return cloned object or original object if we didn't clone it.
 */
protected static Object cloneValue(Object value){
  if (value == null) {
    return null;
  }
  if (value instanceof String) {
    return (value);
  }
  final Class clazz=value.getClass();
  if (clazz.isArray()) {
    final Class type=clazz.getComponentType();
    final int len=Array.getLength(value);
    final Object clonedArray=Array.newInstance(type,len);
    System.arraycopy(value,0,clonedArray,0,len);
    return clonedArray;
  }
  try {
    return (clazz.getMethod("clone",(Class[])null).invoke(value,(Object[])null));
  }
 catch (  final Exception e) {
  }
catch (  final Error e) {
    if (value instanceof Vector) {
      return (((Vector)value).clone());
    }
    if (value instanceof Hashtable) {
      return (((Hashtable)value).clone());
    }
  }
  return (value);
}
 

Example 8

From project android_8, under directory /src/com/google/gson/internal/.

Source file: $Gson$Types.java

  29 
vote

public static Class<?> getRawType(Type type){
  if (type instanceof Class<?>) {
    return (Class<?>)type;
  }
 else   if (type instanceof ParameterizedType) {
    ParameterizedType parameterizedType=(ParameterizedType)type;
    Type rawType=parameterizedType.getRawType();
    checkArgument(rawType instanceof Class);
    return (Class<?>)rawType;
  }
 else   if (type instanceof GenericArrayType) {
    Type componentType=((GenericArrayType)type).getGenericComponentType();
    return Array.newInstance(getRawType(componentType),0).getClass();
  }
 else   if (type instanceof TypeVariable) {
    return Object.class;
  }
 else   if (type instanceof WildcardType) {
    return getRawType(((WildcardType)type).getUpperBounds()[0]);
  }
 else {
    String className=type == null ? "null" : type.getClass().getName();
    throw new IllegalArgumentException("Expected a Class, ParameterizedType, or " + "GenericArrayType, but <" + type + "> is of type "+ className);
  }
}
 

Example 9

From project android_build, under directory /tools/droiddoc/src/.

Source file: DroidDoc.java

  29 
vote

/** 
 * Filters out hidden elements.
 */
private static Object filterHidden(Object o,Class<?> expected){
  if (o == null) {
    return null;
  }
  Class type=o.getClass();
  if (type.getName().startsWith("com.sun.")) {
    return Proxy.newProxyInstance(type.getClassLoader(),type.getInterfaces(),new HideHandler(o));
  }
 else   if (o instanceof Object[]) {
    Class<?> componentType=expected.getComponentType();
    Object[] array=(Object[])o;
    List<Object> list=new ArrayList<Object>(array.length);
    for (    Object entry : array) {
      if ((entry instanceof Doc) && isHidden((Doc)entry)) {
        continue;
      }
      list.add(filterHidden(entry,componentType));
    }
    return list.toArray((Object[])Array.newInstance(componentType,list.size()));
  }
 else {
    return o;
  }
}
 

Example 10

From project android_external_easymock, under directory /src/org/easymock/internal/.

Source file: ArgumentToString.java

  29 
vote

public static void appendArgument(Object value,StringBuffer buffer){
  if (value == null) {
    buffer.append("null");
  }
 else   if (value instanceof String) {
    buffer.append("\"");
    buffer.append(value);
    buffer.append("\"");
  }
 else   if (value instanceof Character) {
    buffer.append("'");
    buffer.append(value);
    buffer.append("'");
  }
 else   if (value.getClass().isArray()) {
    buffer.append("[");
    for (int i=0; i < Array.getLength(value); i++) {
      if (i > 0) {
        buffer.append(", ");
      }
      appendArgument(Array.get(value,i),buffer);
    }
    buffer.append("]");
  }
 else {
    buffer.append(value);
  }
}
 

Example 11

From project android_packages_apps_Gallery3D, under directory /src/com/cooliris/media/.

Source file: LongSparseArray.java

  29 
vote

/** 
 * Returns an empty array of the specified type. The intent is that it will return the same empty array every time to avoid reallocation, although this is not guaranteed.
 */
@SuppressWarnings("unchecked") public static <T>T[] emptyArray(Class<T> kind){
  if (kind == Object.class) {
    return (T[])EMPTY;
  }
  int bucket=((System.identityHashCode(kind) / 8) & 0x7FFFFFFF) % CACHE_SIZE;
  Object cache=sCache[bucket];
  if (cache == null || cache.getClass().getComponentType() != kind) {
    cache=Array.newInstance(kind,0);
    sCache[bucket]=cache;
  }
  return (T[])cache;
}
 

Example 12

From project android_packages_apps_TouchWiz30Launcher, under directory /src/com/sec/android/app/twlauncher/.

Source file: CellLayout.java

  29 
vote

void findVacantCellsFromOccupied(boolean aflag[],int i,int j){
  if (cellX < 0 || cellY < 0) {
    maxVacantSpanXSpanY=0x80000000;
    maxVacantSpanX=0x80000000;
    maxVacantSpanYSpanX=0x80000000;
    maxVacantSpanY=0x80000000;
    clearVacantCells();
  }
 else {
    int ai[]=new int[2];
    ai[0]=i;
    ai[1]=j;
    boolean aflag1[][]=(boolean[][])Array.newInstance(Boolean.TYPE,ai);
    for (int k=0; k < j; k++) {
      for (int l=0; l < i; l++)       aflag1[l][k]=aflag[l + k * i];
    }
    CellLayout.findIntersectingVacantCells(this,cellX,cellY,i,j,aflag1);
  }
}
 

Example 13

From project ANNIS, under directory /annis-gui/src/main/java/org/json/.

Source file: JSONArray.java

  29 
vote

/** 
 * Construct a JSONArray from an array
 * @throws JSONException If not an array.
 */
public JSONArray(Object array) throws JSONException {
  this();
  if (array.getClass().isArray()) {
    int length=Array.getLength(array);
    for (int i=0; i < length; i+=1) {
      this.put(Array.get(array,i));
    }
  }
 else {
    throw new JSONException("JSONArray initial value should be a string or collection or array.");
  }
}
 

Example 14

From project any23, under directory /core/src/main/java/org/apache/any23/validator/.

Source file: XMLValidationReportSerializer.java

  29 
vote

private void printObject(Object o,PrintStream ps) throws SerializationException {
  if (o == null) {
    return;
  }
  if (o instanceof Element) {
    ps.print(o.toString());
    return;
  }
  if (o instanceof Array) {
    Object[] array=(Object[])o;
    if (array.length == 0) {
      return;
    }
    for (    Object a : array) {
      serializeObject(a,ps);
    }
    return;
  }
  if (o instanceof Collection) {
    Collection collection=(Collection)o;
    if (collection.isEmpty()) {
      return;
    }
    for (    Object e : collection) {
      serializeObject(e,ps);
    }
    return;
  }
  ps.print(o.toString());
}
 

Example 15

From project apb, under directory /modules/apb/src/apb/processors/.

Source file: ExcludeDoclet.java

  29 
vote

private static Object process(Object obj,Class expect){
  if (obj == null) {
    return null;
  }
  Class cls=obj.getClass();
  if (cls.getName().startsWith("com.sun.")) {
    return Proxy.newProxyInstance(cls.getClassLoader(),cls.getInterfaces(),new ExcludeHandler(obj));
  }
 else   if (obj instanceof Object[] && expect.isArray()) {
    Class componentType=expect.getComponentType();
    Object[] array=(Object[])obj;
    List<Object> list=new ArrayList<Object>(array.length);
    for (    Object entry : array) {
      if (!(entry instanceof Doc) || !exclude((Doc)entry)) {
        list.add(process(entry,componentType));
      }
    }
    return list.toArray((Object[])Array.newInstance(componentType,list.size()));
  }
 else {
    return obj;
  }
}
 

Example 16

From project ardverk-commons, under directory /src/main/java/org/ardverk/collection/.

Source file: Zipper.java

  29 
vote

@SuppressWarnings("unchecked") public <T>T[] toArray(T[] a){
  T[] dst=a;
  if (dst.length < size) {
    dst=(T[])Array.newInstance(a.getClass().getComponentType(),size);
  }
  int index=0;
  for (Zipper<E> current=this; current != EMPTY; current=current.tail()) {
    dst[index++]=(T)current.element();
  }
  return dst;
}
 

Example 17

From project arquillian-extension-warp, under directory /impl/src/main/java/org/jboss/arquillian/warp/impl/client/separation/.

Source file: SeparateInvocator.java

  29 
vote

private Class<?> adoptType(Class<?> type){
  try {
    if (type.isPrimitive()) {
      return type;
    }
 else     if (type.isArray()) {
      Class<?> componentType=type.getComponentType();
      Class<?> adoptedComponentType=adoptType(componentType);
      return Array.newInstance(adoptedComponentType,0).getClass();
    }
 else {
      return loadSeparatedClassSafely(type);
    }
  }
 catch (  Exception e) {
    throw new IllegalArgumentException("Unable to adopt type of " + type.getName(),e);
  }
}
 

Example 18

From project aunit, under directory /junit/src/main/java/com/toolazydogs/aunit/internal/.

Source file: OptionUtils.java

  29 
vote

/** 
 * Filters the provided options by class returning an array of those option that are instance of the provided class. Before filtering the options are expanded  {@link #expand(Option)}.
 * @param optionType class of the desired options
 * @param options    options to be filtered (can be null or empty array)
 * @param < T >        type of desired options
 * @return array of desired option type (never null). In case that the array of filtered options is null, empty orthere is no option that matches the desired type an empty array is returned
 */
@SuppressWarnings("unchecked") public static <T extends Option>T[] filter(final Class<T> optionType,final Option... options){
  final List<T> filtered=new ArrayList<T>();
  for (  Option option : expand(options)) {
    if (optionType.isAssignableFrom(option.getClass())) {
      filtered.add((T)option);
    }
  }
  final T[] result=(T[])Array.newInstance(optionType,filtered.size());
  return filtered.toArray(result);
}
 

Example 19

From project aviator, under directory /src/main/java/com/googlecode/aviator/runtime/function/seq/.

Source file: SeqCountFunction.java

  29 
vote

@Override public AviatorObject call(Map<String,Object> env,AviatorObject arg1){
  Object value=arg1.getValue(env);
  if (value == null) {
    throw new NullPointerException("null seq");
  }
  Class<?> clazz=value.getClass();
  int size=-1;
  if (Collection.class.isAssignableFrom(clazz)) {
    Collection<?> col=(Collection<?>)value;
    size=col.size();
  }
 else   if (clazz.isArray()) {
    size=Array.getLength(value);
  }
 else {
    throw new IllegalArgumentException(arg1.desc(env) + " is not a seq collection");
  }
  return AviatorLong.valueOf(size);
}
 

Example 20

From project avro, under directory /lang/java/avro/src/main/java/org/apache/avro/reflect/.

Source file: ReflectDatumReader.java

  29 
vote

@Override @SuppressWarnings(value="unchecked") protected Object newArray(Object old,int size,Schema schema){
  Class collectionClass=ReflectData.getClassProp(schema,ReflectData.CLASS_PROP);
  Class elementClass=ReflectData.getClassProp(schema,ReflectData.ELEMENT_PROP);
  if (collectionClass == null && elementClass == null)   return super.newArray(old,size,schema);
  ReflectData data=(ReflectData)getData();
  if (collectionClass != null && !collectionClass.isArray()) {
    if (old instanceof Collection) {
      ((Collection)old).clear();
      return old;
    }
    if (collectionClass.isAssignableFrom(ArrayList.class))     return new ArrayList();
    return data.newInstance(collectionClass,schema);
  }
  if (elementClass == null)   elementClass=data.getClass(schema.getElementType());
  return Array.newInstance(elementClass,size);
}
 

Example 21

From project b3log-latke, under directory /latke/src/main/java/org/json/.

Source file: JSONArray.java

  29 
vote

/** 
 * Construct a JSONArray from an array
 * @throws JSONException If not an array.
 */
public JSONArray(Object array) throws JSONException {
  this();
  if (array.getClass().isArray()) {
    int length=Array.getLength(array);
    for (int i=0; i < length; i+=1) {
      this.put(Array.get(array,i));
    }
  }
 else {
    throw new JSONException("JSONArray initial value should be a string or collection or array.");
  }
}
 

Example 22

From project babel, under directory /src/org/json/.

Source file: JSONArray.java

  29 
vote

/** 
 * Construct a JSONArray from an array
 * @throws JSONException If not an array.
 */
public JSONArray(Object array) throws JSONException {
  this();
  if (array.getClass().isArray()) {
    int length=Array.getLength(array);
    for (int i=0; i < length; i+=1) {
      this.put(Array.get(array,i));
    }
  }
 else {
    throw new JSONException("JSONArray initial value should be a string or collection or array.");
  }
}
 

Example 23

From project BeeQueue, under directory /src/org/beequeue/json/.

Source file: BuzzSchemaBuilder.java

  29 
vote

private void buildEnumClassDef(BuzzAttribute typeId,BuzzClass classDef,Class<?> rawClass){
  try {
    Method valuesMethod=rawClass.getMethod("values",new Class[0]);
    Object arrayOfEnums=valuesMethod.invoke(null,new Object[0]);
    classDef.enumValues=new String[Array.getLength(arrayOfEnums)];
    for (int i=0; i < classDef.enumValues.length; i++) {
      classDef.enumValues[i]=Array.get(arrayOfEnums,i).toString();
    }
  }
 catch (  Exception e) {
    throw new BeeException("extracting values out of enum:",e).addPayload(typeId);
  }
}
 

Example 24

From project BetterShop_1, under directory /src/me/jascotty2/lib/util/.

Source file: ArrayManip.java

  29 
vote

@SuppressWarnings("unchecked") public static <T>T[] arrayConcat(T arr1[],T arr2[]){
  if (arr1 == null && arr2 == null) {
    return null;
  }
 else   if (arr1 == null || arr1.length == 0) {
    return arr2;
  }
 else   if (arr2 == null || arr2.length == 0) {
    return arr1;
  }
  T[] ret=(T[])Array.newInstance(arr1.getClass().getComponentType(),arr1.length + arr2.length);
  System.arraycopy(arr1,0,ret,0,arr1.length);
  System.arraycopy(arr2,0,ret,arr1.length,arr2.length);
  return ret;
}
 

Example 25

From project Blitz, under directory /src/com/laxser/blitz/lama/core/.

Source file: GenericUtils.java

  29 
vote

/** 
 * ????, ????, ????: Generic ??????????????????????
 * @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];
    for (int i=0; i < actualTypes.length; i++) {
      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();
      }
    }
    return actualClasses;
  }
  return EMPTY_CLASSES;
}
 

Example 26

From project Blueprint, under directory /blueprint-core/src/main/java/org/codemined/blueprint/.

Source file: Deserializer.java

  29 
vote

private <T>T deserializeArray(Class<T> type,ConfigTree<?> cfg){
  Class<?> elementType=type.getComponentType();
  List<? extends ConfigTree<?>> elements=cfg.getList();
  Object array=Array.newInstance(elementType,elements.size());
  for (int i=0; i < elements.size(); i++) {
    if (elementType.isPrimitive()) {
      Array.set(array,i,deserializeSimpleType(Types.boxed(elementType),elements.get(i)));
    }
 else {
      Array.set(array,i,deserialize(elementType,null,"[" + i + "]",elements.get(i)));
    }
  }
  return type.cast(array);
}
 

Example 27

From project blueprint-namespaces, under directory /blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/.

Source file: AggregateConverter.java

  29 
vote

private Object convertToCollection(Object obj,ReifiedType type) throws Exception {
  ReifiedType valueType=type.getActualTypeArgument(0);
  Collection newCol=(Collection)ReflectionUtils.newInstance(blueprintContainer.getAccessControlContext(),CollectionRecipe.getCollection(toClass(type)));
  if (obj.getClass().isArray()) {
    for (int i=0; i < Array.getLength(obj); i++) {
      try {
        newCol.add(convert(Array.get(obj,i),valueType));
      }
 catch (      Exception t) {
        throw new Exception("Unable to convert from " + obj + " to "+ type+ "(error converting array element)",t);
      }
    }
  }
 else {
    for (    Object item : (Collection)obj) {
      try {
        newCol.add(convert(item,valueType));
      }
 catch (      Exception t) {
        throw new Exception("Unable to convert from " + obj + " to "+ type+ "(error converting collection entry)",t);
      }
    }
  }
  return newCol;
}
 

Example 28

From project Bukkit-Plugin-Utilties, under directory /src/main/java/de/xzise/.

Source file: MinecraftUtil.java

  29 
vote

/** 
 * Checks if an object is set. Set mean at least ??ot null?. Following objects will be checked separate: <blockquote> <table> <tr> <th>Type</th> <th>Tests</th> </tr> <tr> <td>String</td> <td>not <tt> {@link String#isEmpty()}</tt></td> </tr> <tr> <td>Collection&lt;?&gt;</td> <td>not <tt> {@link Collection#isEmpty()}</tt></td> </tr> <tr> <td>Map&lt;?, ?&gt;</td> <td>not <tt> {@link Map#isEmpty()}</tt></td> </tr> <tr> <td>Any array</td> <td>Arraylength is positive</td> </tr> </table> </blockquote>
 * @param o The tested object.
 * @return If the object is not empty.
 * @since 1.0
 */
public static boolean isSet(Object o){
  if (o == null) {
    return false;
  }
  try {
    if (o instanceof String) {
      return !((String)o).isEmpty();
    }
 else     if (o instanceof Collection<?>) {
      return !((Collection<?>)o).isEmpty();
    }
 else     if (o instanceof Map<?,?>) {
      return !((Map<?,?>)o).isEmpty();
    }
 else     if (o.getClass().isArray()) {
      return Array.getLength(o) > 0;
    }
 else {
      return true;
    }
  }
 catch (  Exception e) {
    return false;
  }
}
 

Example 29

From project byteman, under directory /agent/src/main/java/org/jboss/byteman/rule/expression/.

Source file: ArrayExpression.java

  29 
vote

public Object interpret(HelperAdapter helper) throws ExecuteException {
  try {
    Object value=arrayRef.interpret(helper);
    Type nextType=arrayRef.getType();
    for (    Expression expr : idxList) {
      int idx=((Number)expr.interpret(helper)).intValue();
      if (value == null) {
        throw new ExecuteException("ArrayExpression.interpret : attempted array indirection through null value " + arrayRef.token.getText() + getPos());
      }
      value=Array.get(value,idx);
      nextType=nextType.getBaseType();
    }
    return value;
  }
 catch (  ExecuteException e) {
    throw e;
  }
catch (  IllegalArgumentException e) {
    throw new ExecuteException("ArrayExpression.interpret : failed to evaluate expression " + arrayRef.token.getText() + getPos(),e);
  }
catch (  ArrayIndexOutOfBoundsException e) {
    throw new ExecuteException("ArrayExpression.interpret : invalid index for array " + arrayRef.token.getText() + getPos(),e);
  }
catch (  ClassCastException e) {
    throw new ExecuteException("ArrayExpression.interpret : invalid index dereferencing array " + arrayRef.token.getText() + getPos(),e);
  }
catch (  Exception e) {
    throw new ExecuteException("ArrayExpression.interpret : unexpected exception dereferencing array " + arrayRef.token.getText() + getPos(),e);
  }
}
 

Example 30

From project capedwarf-green, under directory /common/src/main/java/org/jboss/capedwarf/common/env/.

Source file: AbstractEnvironment.java

  29 
vote

/** 
 * Make a JSON text of an Object value. If the object has an value.toJSONString() method, then that method will be used to produce the JSON text. The method is required to produce a strictly conforming text. If the object does not contain a toJSONString method (which is the most common case), then a text will be produced by other means. If the value is an array or Collection, then a JSONArray will be made from it and its toJSONString method will be called. If the value is a MAP, then a JSONObject will be made from it and its toJSONString method will be called. Otherwise, the value's toString method will be called, and the result will be quoted. <p/> <p/> Warning: This method assumes that the data structure is acyclical.
 * @param value The value to be serialized.
 * @return a printable, displayable, transmittablerepresentation of the object, beginning with <code>{</code>&nbsp;<small>(left brace)</small> and ending with <code>}</code>&nbsp;<small>(right brace)</small>.
 * @throws JSONException If the value is or contains an invalid number.
 */
static String valueToString(Object value) throws JSONException {
  if (value == null) {
    return "null";
  }
  if (value instanceof Number) {
    return JSONObject.numberToString((Number)value);
  }
  if (value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) {
    return value.toString();
  }
  if (value instanceof Map) {
    return new JSONObject((Map)value).toString();
  }
  if (value instanceof Collection) {
    return new JSONArray((Collection)value).toString();
  }
  if (value.getClass().isArray()) {
    Collection<Object> collection=new ArrayList<Object>();
    for (int i=0; i < Array.getLength(value); i++)     collection.add(Array.get(value,i));
    return new JSONArray(collection).toString();
  }
  return JSONObject.quote(value.toString());
}
 

Example 31

From project cdh-mapreduce-ext, under directory /src/main/java/org/apache/hadoop/mapreduce/lib/partition/.

Source file: TotalOrderPartitioner.java

  29 
vote

/** 
 * Read the cut points from the given IFile.
 * @param fs The file system
 * @param p The path to read
 * @param keyClass The map output key class
 * @param job The job config
 * @throws IOException
 */
@SuppressWarnings("unchecked") private K[] readPartitions(FileSystem fs,Path p,Class<K> keyClass,Configuration conf) throws IOException {
  SequenceFile.Reader reader=new SequenceFile.Reader(fs,p,conf);
  ArrayList<K> parts=new ArrayList<K>();
  K key=ReflectionUtils.newInstance(keyClass,conf);
  NullWritable value=NullWritable.get();
  while (reader.next(key,value)) {
    parts.add(key);
    key=ReflectionUtils.newInstance(keyClass,conf);
  }
  reader.close();
  return parts.toArray((K[])Array.newInstance(keyClass,parts.size()));
}
 

Example 32

From project ceres, under directory /ceres-binding/src/main/java/com/bc/ceres/binding/converters/.

Source file: ArrayConverter.java

  29 
vote

@Override public Object parse(String text) throws ConversionException {
  if (text.isEmpty()) {
    return null;
  }
  StringTokenizer st=new StringTokenizer(text,SEPARATOR);
  int length=st.countTokens();
  Object array=Array.newInstance(arrayType.getComponentType(),length);
  for (int i=0; i < length; i++) {
    Object component=componentConverter.parse(st.nextToken().replace(SEPARATOR_ESC,SEPARATOR));
    Array.set(array,i,component);
  }
  return array;
}
 

Example 33

From project chromattic, under directory /common/src/main/java/org/chromattic/common/collection/wrapped/.

Source file: WrappedArrayList.java

  29 
vote

public static <E,A>WrappedArrayList<E,A> create(Class<E> elementType,Class<?> componentType,int size){
  if (elementType == null) {
    throw new NullPointerException("No null element type can be provided");
  }
  if (size < 0) {
    throw new IllegalArgumentException("No negative sized array can be created (" + size + ")");
  }
  return wrap(elementType,Array.newInstance(componentType,size));
}
 

Example 34

From project Cilia_1, under directory /framework/runtime/src/main/java/fr/liglab/adele/cilia/admin/util/.

Source file: JSONArray.java

  29 
vote

/** 
 * Construct a JSONArray from an array
 * @throws JSONException If not an array.
 */
public JSONArray(Object array) throws JSONException {
  this();
  if (array.getClass().isArray()) {
    int length=Array.getLength(array);
    for (int i=0; i < length; i+=1) {
      this.put(JSONObject.wrap(Array.get(array,i)));
    }
  }
 else {
    throw new JSONException("JSONArray initial value should be a string or collection or array.");
  }
}
 

Example 35

From project CircDesigNA, under directory /src/circdesigna/abstractDesigner/.

Source file: BlockDesigner.java

  29 
vote

/** 
 * Initializes this designer with one member, and numCopies-1 number of newly created members with that same seed. Necessary before designing.
 */
public void initialize(T init,int popSize){
  populationSize=popSize;
  population_mutable=(T[])Array.newInstance(init.getClass(),popSize);
  for (int k=0; k < populationSize; k++) {
    if (k != 0) {
      population_mutable[k]=init.designerCopyConstructor(k);
    }
 else {
      population_mutable[k]=init;
    }
  }
  progressInIteration=0;
}
 

Example 36

From project CIShell, under directory /clients/remoting/org.cishell.reference.remoting/src/org/cishell/reference/remoting/.

Source file: RemotingClient.java

  29 
vote

protected long[] toLongArray(Object obj){
  if (obj == null) {
    return null;
  }
  long[] la;
  if (obj instanceof SoapObject) {
    SoapObject so=(SoapObject)obj;
    la=new long[so.getPropertyCount()];
    for (int i=0; i < la.length; i++) {
      la[i]=new Long(so.getProperty(i).toString()).longValue();
    }
  }
 else {
    la=new long[Array.getLength(obj)];
    for (int i=0; i < la.length; i++) {
      la[i]=((Long)Array.get(obj,i)).longValue();
    }
  }
  return la;
}
 

Example 37

From project clj-ds, under directory /src/main/java/com/trifork/clj_ds/.

Source file: ArraySeq.java

  29 
vote

static ISeq createFromObject(Object array){
  if (array == null || Array.getLength(array) == 0)   return null;
  Class aclass=array.getClass();
  if (aclass == int[].class)   return new ArraySeq_int(null,(int[])array,0);
  if (aclass == float[].class)   return new ArraySeq_float(null,(float[])array,0);
  if (aclass == double[].class)   return new ArraySeq_double(null,(double[])array,0);
  if (aclass == long[].class)   return new ArraySeq_long(null,(long[])array,0);
  if (aclass == byte[].class)   return new ArraySeq_byte(null,(byte[])array,0);
  if (aclass == char[].class)   return new ArraySeq_char(null,(char[])array,0);
  if (aclass == boolean[].class)   return new ArraySeq_boolean(null,(boolean[])array,0);
  return new ArraySeq(array,0);
}
 

Example 38

From project clojure, under directory /src/jvm/clojure/lang/.

Source file: ArraySeq.java

  29 
vote

static ISeq createFromObject(Object array){
  if (array == null || Array.getLength(array) == 0)   return null;
  Class aclass=array.getClass();
  if (aclass == int[].class)   return new ArraySeq_int(null,(int[])array,0);
  if (aclass == float[].class)   return new ArraySeq_float(null,(float[])array,0);
  if (aclass == double[].class)   return new ArraySeq_double(null,(double[])array,0);
  if (aclass == long[].class)   return new ArraySeq_long(null,(long[])array,0);
  if (aclass == byte[].class)   return new ArraySeq_byte(null,(byte[])array,0);
  if (aclass == char[].class)   return new ArraySeq_char(null,(char[])array,0);
  if (aclass == boolean[].class)   return new ArraySeq_boolean(null,(boolean[])array,0);
  return new ArraySeq(array,0);
}
 

Example 39

From project Cloud9, under directory /src/dist/org/json/.

Source file: JSONArray.java

  29 
vote

/** 
 * Construct a JSONArray from an array
 * @throws JSONException If not an array.
 */
public JSONArray(Object array) throws JSONException {
  this();
  if (array.getClass().isArray()) {
    int length=Array.getLength(array);
    for (int i=0; i < length; i+=1) {
      this.put(Array.get(array,i));
    }
  }
 else {
    throw new JSONException("JSONArray initial value should be a string or collection or array.");
  }
}
 

Example 40

From project cloudify, under directory /restful/src/main/java/org/cloudifysource/rest/out/.

Source file: OutputUtils.java

  29 
vote

public static Object[] getArray(Object val){
  int arrlength=Array.getLength(val);
  Object[] outputArray=new Object[arrlength];
  for (int i=0; i < arrlength; ++i) {
    outputArray[i]=Array.get(val,i);
  }
  return outputArray;
}
 

Example 41

From project collections-generic, under directory /src/java/org/apache/commons/collections15/bag/.

Source file: AbstractMapBag.java

  29 
vote

/** 
 * Returns an array of all of this bag's elements.
 * @param array the array to populate
 * @return an array of all of this bag's elements
 */
public Object[] toArray(Object[] array){
  int size=size();
  if (array.length < size) {
    array=(Object[])Array.newInstance(array.getClass().getComponentType(),size);
  }
  int i=0;
  Iterator<E> it=map.keySet().iterator();
  while (it.hasNext()) {
    E current=it.next();
    for (int index=getCount(current); index > 0; index--) {
      array[i++]=current;
    }
  }
  if (array.length > size) {
    array[size]=null;
  }
  return array;
}
 

Example 42

From project cometd, under directory /cometd-java/cometd-java-server/src/main/java/org/cometd/server/filter/.

Source file: JSONDataFilter.java

  29 
vote

protected Object filterArray(ServerSession from,ServerChannel to,Object array){
  if (array == null)   return null;
  int length=Array.getLength(array);
  for (int i=0; i < length; i++)   Array.set(array,i,filter(from,to,Array.get(array,i)));
  return array;
}
 

Example 43

From project commons-json, under directory /src/commons/json/.

Source file: JsonSerializer.java

  29 
vote

/** 
 * ??????
 * @param src
 * @return
 */
JsonAware jsonArrayMapping(Object src){
  if (src == null) {
    return serializeNulls ? JsonNull.getInstance() : null;
  }
  JsonArray target=new JsonArray();
  if (src.getClass().isArray()) {
    for (int i=0; i < Array.getLength(src); i++) {
      Object element=Array.get(src,i);
      if (element == null) {
        target.add(JsonNull.getInstance());
      }
 else {
        JsonAware jsonElement=typeMapping(element);
        target.add(jsonElement);
      }
    }
    return target;
  }
  for (  Object element : (Iterable)src) {
    if (element == null) {
      target.add(JsonNull.getInstance());
    }
 else {
      JsonAware jsonElement=typeMapping(element);
      target.add(jsonElement);
    }
  }
  return target;
}
 

Example 44

From project commons-pool, under directory /src/java/org/apache/commons/pool/impl/.

Source file: CursorableLinkedList.java

  29 
vote

/** 
 * Returns an array containing all of the elements in this list in proper sequence; the runtime type of the returned array is that of the specified array. Obeys the general contract of the {@link Collection#toArray()} method.
 * @param a      the array into which the elements of this list are tobe stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.
 * @return an array containing the elements of this list.
 * @exception ArrayStoreException if the runtime type of the specified array is not a supertype of the runtime type of every element in this list.
 */
public Object[] toArray(Object a[]){
  if (a.length < _size) {
    a=(Object[])Array.newInstance(a.getClass().getComponentType(),_size);
  }
  int i=0;
  for (Listable elt=_head.next(), past=null; null != elt && past != _head.prev(); elt=(past=elt).next()) {
    a[i++]=elt.value();
  }
  if (a.length > _size) {
    a[_size]=null;
  }
  return a;
}
 

Example 45

From project common_1, under directory /src/main/java/org/powertac/common/state/.

Source file: StateLogging.java

  29 
vote

@SuppressWarnings("rawtypes") private void writeArg(StringBuffer buf,Object arg){
  Long argId=findId(arg);
  if (argId != null)   buf.append(argId.toString());
 else   if (arg == null)   buf.append("null");
 else   if (arg instanceof Collection) {
    buf.append("(");
    String delimiter="";
    for (    Object item : (Collection)arg) {
      buf.append(delimiter);
      writeArg(buf,item);
      delimiter=",";
    }
    buf.append(")");
  }
 else   if (arg.getClass().isArray()) {
    buf.append("[");
    int length=Array.getLength(arg);
    for (int index=0; index < length; index++) {
      writeArg(buf,Array.get(arg,index));
      if (index < length - 1) {
        buf.append(",");
      }
    }
    buf.append("]");
  }
 else {
    buf.append(arg.toString());
  }
}
 

Example 46

From project Core_2, under directory /shell/src/main/java/org/jboss/forge/shell/util/.

Source file: GeneralUtils.java

  29 
vote

@SuppressWarnings("unchecked") public static <T>T[] join(Class<T> type,T[] front,T... back){
  Assert.notNull(type,"Type must not be null.");
  Assert.notNull(front,"Target array must not be null.");
  Assert.notNull(back,"Source array must not be null.");
  T[] dest=front;
  int size=0;
  if (front != null)   size=front.length;
  if (back != null)   size+=back.length;
  dest=(T[])Array.newInstance(type,size);
  if (dest.length > 1) {
    System.arraycopy(front,0,dest,0,front.length);
    System.arraycopy(back,0,dest,front.length,back.length);
  }
  return dest;
}
 

Example 47

From project core_4, under directory /api/src/test/java/org/ajax4jsf/javascript/.

Source file: ResponseWriterWrapperTest.java

  29 
vote

private static char[] expectSingleChar(final char c){
  reportMatcher(new IArgumentMatcher(){
    private String failureMessage;
    public void appendTo(    StringBuffer sb){
      sb.append(failureMessage);
    }
    public boolean matches(    Object o){
      if (!(o instanceof char[])) {
        failureMessage="Array of chars expected as argument";
      }
 else {
        if (Array.getLength(o) == 0) {
          failureMessage="Array should be of non-zero length";
        }
 else {
          if (Array.getChar(o,0) != c) {
            failureMessage="[" + c + "] expected as [0] char";
          }
        }
      }
      return failureMessage == null;
    }
  }
);
  return null;
}
 

Example 48

From project core_5, under directory /exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate/.

Source file: HibernateListAccess.java

  29 
vote

/** 
 * {@inheritDoc}
 */
@SuppressWarnings("unchecked") public E[] load(int index,int length) throws Exception, IllegalArgumentException {
  final Session session=service.openSession();
  if (index < 0) {
    throw new IllegalArgumentException("Illegal index: index must be a positive number");
  }
  if (length < 0) {
    throw new IllegalArgumentException("Illegal length: length must be a positive number");
  }
  Query query=SecurityHelper.doPrivilegedAction(new PrivilegedAction<Query>(){
    public Query run(){
      return session.createQuery(findQuery);
    }
  }
);
  bindFields(query);
  E[] entities=(E[])Array.newInstance(query.getReturnTypes()[0].getReturnedClass(),length);
  Iterator<E> results=query.iterate();
  for (int p=0, counter=0; counter < length; p++) {
    if (!results.hasNext()) {
      throw new IllegalArgumentException("Illegal index or length: sum of the index and the length cannot be greater than the list size");
    }
    E result=results.next();
    if (p >= index) {
      entities[counter++]=result;
    }
  }
  return entities;
}
 

Example 49

From project core_7, under directory /src/main/java/io/s4/util/.

Source file: LoadGenerator.java

  29 
vote

@SuppressWarnings("unchecked") public Object makeArray(Property property,JSONArray jsonArray){
  Property componentProperty=property.getComponentProperty();
  Class clazz=componentProperty.getType();
  int size=jsonArray.length();
  Object array=Array.newInstance(clazz,size);
  try {
    for (int i=0; i < size; i++) {
      Object value=jsonArray.get(i);
      Object adjustedValue=makeSettableValue(componentProperty,value);
      Array.set(array,i,adjustedValue);
    }
  }
 catch (  JSONException je) {
    throw new RuntimeException(je);
  }
  return array;
}
 

Example 50

From project cp-common-utils, under directory /src/com/clarkparsia/common/base/.

Source file: HashCodeUtil.java

  29 
vote

/** 
 * <code>aObject</code> is a possibly-null object field, and possibly an array. If <code>aObject</code> is an array, then each element may be a primitive or a possibly-null object.
 */
public static int hash(int aSeed,Object aObject){
  int result=aSeed;
  if (aObject == null) {
    result=hash(result,0);
  }
 else   if (!isArray(aObject)) {
    result=hash(result,aObject.hashCode());
  }
 else {
    int length=Array.getLength(aObject);
    for (int idx=0; idx < length; ++idx) {
      Object item=Array.get(aObject,idx);
      result=hash(result,item);
    }
  }
  return result;
}
 

Example 51

From project crunch, under directory /scrunch/src/main/java/org/apache/scrunch/.

Source file: ScalaSafeReflectDatumReader.java

  29 
vote

@Override @SuppressWarnings(value="unchecked") protected Object newArray(Object old,int size,Schema schema){
  ScalaSafeReflectData data=ScalaSafeReflectData.get();
  Class collectionClass=ScalaSafeReflectData.getClassProp(schema,ScalaSafeReflectData.CLASS_PROP);
  if (collectionClass != null) {
    if (old instanceof Collection) {
      ((Collection)old).clear();
      return old;
    }
    if (scala.collection.Iterable.class.isAssignableFrom(collectionClass) || collectionClass.isAssignableFrom(ArrayList.class)) {
      return new ArrayList();
    }
    return data.newInstance(collectionClass,schema);
  }
  Class elementClass=ScalaSafeReflectData.getClassProp(schema,ScalaSafeReflectData.ELEMENT_PROP);
  if (elementClass == null)   elementClass=data.getClass(schema.getElementType());
  return Array.newInstance(elementClass,size);
}
 

Example 52

From project Cyborg, under directory /src/main/java/com/alta189/cyborg/api/util/config/ini/.

Source file: IniConfiguration.java

  29 
vote

/** 
 * Returns the String representation of a configuration value for writing to the file
 * @param value
 * @return
 */
public String toStringValue(Object value){
  if (value == null) {
    return "null";
  }
  if (value.getClass().isArray()) {
    List<Object> toList=new ArrayList<Object>();
    final int length=Array.getLength(value);
    for (int i=0; i < length; ++i) {
      toList.add(Array.get(value,i));
    }
    value=toList;
  }
  if (value instanceof Collection) {
    StringBuilder builder=new StringBuilder();
    for (    Object obj : (Collection<?>)value) {
      if (builder.length() > 0) {
        builder.append(", ");
      }
      builder.append(obj.toString());
    }
    return builder.toString();
  }
 else {
    String strValue=value.toString();
    if (strValue.contains(",")) {
      strValue='"' + strValue + '"';
    }
    return strValue;
  }
}
 

Example 53

From project Danroth, under directory /src/main/java/org/yaml/snakeyaml/constructor/.

Source file: BaseConstructor.java

  29 
vote

protected Object constructArrayStep2(SequenceNode node,Object array){
  int index=0;
  for (  Node child : node.getValue()) {
    Array.set(array,index++,constructObject(child));
  }
  return array;
}
 

Example 54

From project datasalt-utils, under directory /src/contrib/java/org/apache/velocity/tools/generic/.

Source file: ExtendedListTool.java

  29 
vote

/** 
 * Converts an array object into a List. <ul> <li> If the object is already a List, it will return the object itself. </li> <li> If the object is an array of an Object, it will return a List of the elements. </li> <li> If the object is an array of a primitive type, it will return a List of the elements wrapped in their wrapper class. </li> <li> If the object is none of the above, it will return null. </li> </ul>
 * @param array an array object.
 * @return the converted java.util.List.
 */
public List toList(Object array){
  if (this.isList(array)) {
    return (List)array;
  }
  if (!this.isArray(array)) {
    return null;
  }
  int length=Array.getLength(array);
  List asList=new ArrayList(length);
  for (int index=0; index < length; ++index) {
    asList.add(Array.get(array,index));
  }
  return asList;
}
 

Example 55

From project dawn-common, under directory /org.dawb.hdf5/src/ncsa/hdf/object/fits/.

Source file: FitsDataset.java

  29 
vote

private int get1DLength(Object data) throws Exception {
  if (!data.getClass().isArray()) {
    return 1;
  }
  int len=Array.getLength(data);
  int total=0;
  for (int i=0; i < len; i++) {
    total+=get1DLength(Array.get(data,i));
  }
  return total;
}
 

Example 56

From project dawn-isencia, under directory /com.isencia.passerelle.commons/src/main/java/com/isencia/util/.

Source file: ArrayUtil.java

  29 
vote

/** 
 * <code>aArray</code> is a possibly-null array whose elements are primitives or objects; arrays of arrays are also valid, in which case <code>aArray</code> is rendered in a nested, recursive fashion. The array delimiter and start/end characters may be customized. When any of these is null, the default value is used, i.e. </ul> <li>array delimiter (",") <li> start/end characters ("[" and "]") <li>null representation ("null") </ul>
 * @param aArray
 * @param startChar
 * @param endChar
 * @param separator
 * @param nullRepresentation
 * @return
 */
public static String toString(Object aArray,String startChar,String endChar,String separator,String nullRepresentation){
  if (nullRepresentation == null)   nullRepresentation=NULL;
  if (aArray == null)   return nullRepresentation;
  checkObjectIsArray(aArray);
  if (startChar == null)   startChar=START_CHAR;
  if (endChar == null)   endChar=END_CHAR;
  if (separator == null)   separator=SEPARATOR;
  StringBuffer result=new StringBuffer(startChar);
  int length=Array.getLength(aArray);
  for (int idx=0; idx < length; ++idx) {
    Object item=Array.get(aArray,idx);
    if (isNonNullArray(item)) {
      result.append(toString(item,startChar,endChar,separator,nullRepresentation));
    }
 else {
      result.append(item);
    }
    if (!isLastItem(idx,length)) {
      result.append(separator);
    }
  }
  result.append(endChar);
  return result.toString();
}
 

Example 57

From project DeuceSTM, under directory /src/java/org/deuce/trove/.

Source file: THashSet.java

  29 
vote

/** 
 * Returns a typed array of the objects in the set.
 * @param a an <code>Object[]</code> value
 * @return an <code>Object[]</code> value
 */
public <T>T[] toArray(T[] a){
  int size=size();
  if (a.length < size)   a=(T[])Array.newInstance(a.getClass().getComponentType(),size);
  forEach(new ToObjectArrayProcedure(a));
  if (a.length > size) {
    a[size]=null;
  }
  return a;
}
 

Example 58

From project dozer, under directory /core/src/main/java/org/dozer/.

Source file: MappingProcessor.java

  29 
vote

private Object mapArrayToArray(Object srcObj,Object srcCollectionValue,FieldMap fieldMap,Object destObj){
  Class destEntryType=fieldMap.getDestFieldType(destObj.getClass()).getComponentType();
  int size=Array.getLength(srcCollectionValue);
  if (CollectionUtils.isPrimitiveArray(srcCollectionValue.getClass())) {
    return addToPrimitiveArray(srcObj,fieldMap,size,srcCollectionValue,destObj,destEntryType);
  }
 else {
    List<?> list=Arrays.asList((Object[])srcCollectionValue);
    List<?> returnList;
    if (!destEntryType.getName().equals(BASE_CLASS)) {
      returnList=addOrUpdateToList(srcObj,fieldMap,list,destObj,destEntryType);
    }
 else {
      returnList=addOrUpdateToList(srcObj,fieldMap,list,destObj,null);
    }
    return CollectionUtils.convertListToArray(returnList,destEntryType);
  }
}
 

Example 59

From project droid-fu, under directory /src/main/java/com/github/droidfu/support/.

Source file: ArraySupport.java

  29 
vote

@SuppressWarnings("unchecked") public static <T>T[] join(T[] head,T[] tail){
  if (head == null) {
    return tail;
  }
  if (tail == null) {
    return head;
  }
  Class<?> type=head.getClass().getComponentType();
  T[] result=(T[])Array.newInstance(type,head.length + tail.length);
  System.arraycopy(head,0,result,0,head.length);
  System.arraycopy(tail,0,result,head.length,tail.length);
  return result;
}
 

Example 60

From project droolsjbpm-integration, under directory /drools-camel/src/main/java/org/drools/camel/component/.

Source file: FastCloner.java

  29 
vote

/** 
 * copies all properties from src to dest. Src and dest can be of different class, provided they contain same field names
 * @param src the source object
 * @param dest the destination object which must contain as minimul all the fields of src
 */
public <T,E extends T>void copyPropertiesOfInheritedClass(final T src,final E dest){
  if (src == null) {
    throw new IllegalArgumentException("src can't be null");
  }
  if (dest == null) {
    throw new IllegalArgumentException("dest can't be null");
  }
  final Class<? extends Object> srcClz=src.getClass();
  final Class<? extends Object> destClz=dest.getClass();
  if (srcClz.isArray()) {
    if (!destClz.isArray()) {
      throw new IllegalArgumentException("can't copy from array to non-array class " + destClz);
    }
    final int length=Array.getLength(src);
    for (int i=0; i < length; i++) {
      final Object v=Array.get(src,i);
      Array.set(dest,i,v);
    }
    return;
  }
  final List<Field> fields=allFields(srcClz);
  for (  final Field field : fields) {
    if (!Modifier.isStatic(field.getModifiers())) {
      try {
        final Object fieldObject=field.get(src);
        field.set(dest,fieldObject);
      }
 catch (      final IllegalArgumentException e) {
        throw new RuntimeException(e);
      }
catch (      final IllegalAccessException e) {
        throw new RuntimeException(e);
      }
    }
  }
}
 

Example 61

From project droolsjbpm-tools, under directory /drools-eclipse/org.drools.eclipse/src/main/java/org/drools/eclipse/flow/common/editor/.

Source file: ObjectInputStreamWithLoader.java

  29 
vote

/** 
 * Use the given ClassLoader rather than using the system class
 */
protected Class resolveClass(ObjectStreamClass classDesc) throws IOException, ClassNotFoundException {
  String cname=classDesc.getName();
  if (cname.startsWith("[")) {
    Class component=null;
    int dcount;
    for (dcount=1; cname.charAt(dcount) == '['; dcount++)     ;
    if (cname.charAt(dcount) == 'L') {
      String className=cname.substring(dcount + 1,cname.length() - 1);
      component=loader.loadClass(className);
    }
 else {
      if (cname.length() != dcount + 1) {
        throw new ClassNotFoundException(cname);
      }
      component=primitiveType(cname.charAt(dcount));
    }
    int dim[]=new int[dcount];
    for (int i=0; i < dcount; i++) {
      dim[i]=0;
    }
    return Array.newInstance(component,dim).getClass();
  }
  return loader.loadClass(cname);
}
 

Example 62

From project dynalink, under directory /src/main/java/org/dynalang/dynalink/beans/.

Source file: BeanLinker.java

  29 
vote

@SuppressWarnings("unused") private static final boolean rangeCheck(Object array,Object index){
  if (!(index instanceof Number)) {
    return false;
  }
  final int intIndex=((Number)index).intValue();
  return 0 <= intIndex && intIndex < Array.getLength(array);
}
 

Example 63

From project EasySOA, under directory /samples/Talend-Airport-Service/SimpleProvider_0.1/SimpleProvider/src/routines/system/.

Source file: JSONObject.java

  29 
vote

/** 
 * Construct a JSONArray from an array
 * @throws JSONException If not an array.
 */
public JSONArray(Object array) throws JSONException {
  this();
  if (array.getClass().isArray()) {
    int length=Array.getLength(array);
    for (int i=0; i < length; i+=1) {
      this.put(JSONObject.wrap(Array.get(array,i)));
    }
  }
 else {
    throw new JSONException("JSONArray initial value should be a string or collection or array.");
  }
}
 

Example 64

From project eclipsefp, under directory /net.sf.eclipsefp.haskell.scion.client/lib/org/json/.

Source file: JSONArray.java

  29 
vote

/** 
 * Construct a JSONArray from an array
 * @throws JSONException If not an array.
 */
public JSONArray(Object array) throws JSONException {
  this();
  if (array.getClass().isArray()) {
    int length=Array.getLength(array);
    for (int i=0; i < length; i+=1) {
      this.put(Array.get(array,i));
    }
  }
 else {
    throw new JSONException("JSONArray initial value should be a string or collection or array.");
  }
}
 

Example 65

From project elasticsearch-osem, under directory /src/main/java/org/elasticsearch/osem/common/springframework/core/.

Source file: GenericTypeResolver.java

  29 
vote

/** 
 * Extract a class instance from given Type.
 */
private static Class extractClass(Class ownerClass,Type arg){
  if (arg instanceof ParameterizedType) {
    return extractClass(ownerClass,((ParameterizedType)arg).getRawType());
  }
 else   if (arg instanceof GenericArrayType) {
    GenericArrayType gat=(GenericArrayType)arg;
    Type gt=gat.getGenericComponentType();
    Class<?> componentClass=extractClass(ownerClass,gt);
    return Array.newInstance(componentClass,0).getClass();
  }
 else   if (arg instanceof TypeVariable) {
    TypeVariable tv=(TypeVariable)arg;
    arg=getTypeVariableMap(ownerClass).get(tv);
    if (arg == null) {
      arg=extractBoundForTypeVariable(tv);
    }
 else {
      arg=extractClass(ownerClass,arg);
    }
  }
  return (arg instanceof Class ? (Class)arg : Object.class);
}
 

Example 66

From project enterprise, under directory /consistency-check/src/main/java/org/neo4j/consistency/checking/full/.

Source file: FullCheck.java

  29 
vote

private static <T extends AbstractBaseRecord>T[] readAllRecords(Class<T> type,RecordStore<T> store){
  @SuppressWarnings("unchecked") T[] records=(T[])Array.newInstance(type,(int)store.getHighId());
  for (int i=0; i < records.length; i++) {
    records[i]=store.forceGetRecord(i);
  }
  return records;
}
 

Example 67

From project eoit, under directory /EOITUtils/src/main/java/android/util/.

Source file: ArrayUtils.java

  29 
vote

/** 
 * Returns an empty array of the specified type.  The intent is that it will return the same empty array every time to avoid reallocation, although this is not guaranteed.
 */
@SuppressWarnings("unchecked") public static <T>T[] emptyArray(Class<T> kind){
  if (kind == Object.class) {
    return (T[])EMPTY;
  }
  int bucket=((System.identityHashCode(kind) / 8) & 0x7FFFFFFF) % CACHE_SIZE;
  Object cache=sCache[bucket];
  if (cache == null || cache.getClass().getComponentType() != kind) {
    cache=Array.newInstance(kind,0);
    sCache[bucket]=cache;
  }
  return (T[])cache;
}
 

Example 68

From project etherpad, under directory /infrastructure/rhino1_7R1/src/org/mozilla/javascript/.

Source file: NativeJavaArray.java

  29 
vote

public NativeJavaArray(Scriptable scope,Object array){
  super(scope,null,ScriptRuntime.ObjectClass);
  Class cl=array.getClass();
  if (!cl.isArray()) {
    throw new RuntimeException("Array expected");
  }
  this.array=array;
  this.length=Array.getLength(array);
  this.cls=cl.getComponentType();
}
 

Example 69

From project fakereplace, under directory /plugins/jbossas/src/main/java/org/fakereplace/integration/jbossas/.

Source file: JBossASClassChangeAware.java

  29 
vote

private void clearJSRResourceCache(){
  final Set<?> caches=InstanceTracker.get(JBossASExtension.RESOURCE_CACHE_CLASS);
  for (  Object cache : caches) {
    try {
      Field field=cache.getClass().getDeclaredField("cache");
      field.setAccessible(true);
      final Class fieldType=field.getType();
      field.set(cache,Array.newInstance(fieldType.getComponentType(),0));
    }
 catch (    Exception e) {
      log.error("Failed to clear JSF resource cache",e);
      e.printStackTrace();
    }
  }
}
 

Example 70

From project fastjson, under directory /src/main/java/com/alibaba/fastjson/parser/deserializer/.

Source file: ArrayDeserializer.java

  29 
vote

@SuppressWarnings("unchecked") private <T>T toObjectArray(DefaultJSONParser parser,Class<T> clazz,JSONArray array){
  if (array == null) {
    return null;
  }
  int size=array.size();
  Class<?> componentType=clazz.getComponentType();
  Object objArray=Array.newInstance(componentType,size);
  for (int i=0; i < size; ++i) {
    Object value=array.get(i);
    if (componentType.isArray()) {
      Object element;
      if (componentType.isInstance(value)) {
        element=value;
      }
 else {
        element=toObjectArray(parser,componentType,(JSONArray)value);
      }
      Array.set(objArray,i,element);
    }
 else {
      Object element=TypeUtils.cast(value,componentType,parser.getConfig());
      Array.set(objArray,i,element);
    }
  }
  array.setRelatedArray(objArray);
  array.setComponentType(componentType);
  return (T)objArray;
}
 

Example 71

From project fest-assert-2.x, under directory /src/main/java/org/fest/assertions/internal/.

Source file: AbstractComparisonStrategy.java

  29 
vote

@Override public boolean arrayContains(Object array,Object value){
  for (int i=0; i < getLength(array); i++) {
    Object element=Array.get(array,i);
    if (areEqual(element,value)) {
      return true;
    }
  }
  return false;
}