Java Code Examples for java.lang.reflect.Array.set()

The following are Jave code examples for showing how to use set() of the java.lang.reflect.Array class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: lams   File: ArrayTypeAdapter.java   Source Code and License Vote up 6 votes
public Object read(JsonReader in) throws IOException {
  if (in.peek() == JsonToken.NULL) {
    in.nextNull();
    return null;
  }

  List<E> list = new ArrayList<E>();
  in.beginArray();
  while (in.hasNext()) {
    E instance = componentTypeAdapter.read(in);
    list.add(instance);
  }
  in.endArray();
  Object array = Array.newInstance(componentType, list.size());
  for (int i = 0; i < list.size(); i++) {
    Array.set(array, i, list.get(i));
  }
  return array;
}
 
Example 2
Project: GameAuthoringEnvironment   File: Reflection.java   Source Code and License Vote up 6 votes
private static Object[] convertArgs (Member function, Class<?>[] formals, Object[] actuals) {
    Object[] results = actuals;
    if (isVarArgs(function)) {
        results = new Object[formals.length];
        int idx = 0;
        for (; idx < formals.length - 1; idx++) {
            // simply copy the basic parameters
            results[idx] = actuals[idx];
        }
        Class<?> type = formals[idx].getComponentType();
        Object varArgs = Array.newInstance(type, actuals.length - formals.length + 1);
        for (; idx < actuals.length; idx++) {
            // fill the varArg array with the remaining parameters
            Array.set(varArgs, idx - formals.length + 1, actuals[idx]);
        }
        results[results.length - 1] = varArgs;
    }
    return results;
}
 
Example 3
Project: letv   File: a.java   Source Code and License Vote up 6 votes
public final Object a(com.google.gson.jpush.b.a aVar) {
    if (aVar.f() == c.i) {
        aVar.j();
        return null;
    }
    List arrayList = new ArrayList();
    aVar.a();
    while (aVar.e()) {
        arrayList.add(this.c.a(aVar));
    }
    aVar.b();
    Object newInstance = Array.newInstance(this.b, arrayList.size());
    for (int i = 0; i < arrayList.size(); i++) {
        Array.set(newInstance, i, arrayList.get(i));
    }
    return newInstance;
}
 
Example 4
Project: data-mediator   File: TypeHandler.java   Source Code and License Vote up 6 votes
@Override
public void read(JsonReader in, GsonProperty property, Object t) throws IOException {
    final Class<?> simpleType = property.getType();

    List list = new ArrayList();
    in.beginArray();
    if (simpleType.isPrimitive() || isBoxedClass(simpleType)) {
        while (in.hasNext()){
            list.add(SupportUtils.readPrimitiveOrItsBox(in, property));
        }
    }else{
        TypeAdapter adapter = getTypeAdapter(simpleType);
        while (in.hasNext()){
            list.add(adapter.read(in));
        }
    }
    //copy to array
    Object array = Array.newInstance(simpleType, list.size());
    for(int i = 0, size = list.size() ; i < size ; i ++){
        Array.set(array, i, list.get(i));
    }
    setValue(property, t, array);
    in.endArray();
}
 
Example 5
Project: openjdk-jdk10   File: MBeanIntrospector.java   Source Code and License Vote up 5 votes
static boolean isValidParameter(Method m, Object value, int paramNo) {
    Class<?> c = m.getParameterTypes()[paramNo];
    try {
        // Following is expensive but we only call this method to determine
        // if an exception is due to an incompatible parameter type.
        // Plain old c.isInstance doesn't work for primitive types.
        Object a = Array.newInstance(c, 1);
        Array.set(a, 0, value);
        return true;
    } catch (IllegalArgumentException e) {
        return false;
    }
}
 
Example 6
Project: jsf-sdk   File: ResolveFieldDeserializer.java   Source Code and License Vote up 5 votes
@SuppressWarnings("unchecked")
public void setValue(Object object, Object value) {
    if (map != null) {
        map.put(key, value);
        return;
    }
    
    if (collection != null) {
        collection.add(value);
        return;
    }
    
    list.set(index, value);

    if (list instanceof JSONArray) {
        JSONArray jsonArray = (JSONArray) list;
        Object array = jsonArray.getRelatedArray();

        if (array != null) {
            int arrayLength = Array.getLength(array);

            if (arrayLength > index) {
                Object item;
                if (jsonArray.getComponentType() != null) {
                    item = TypeUtils.cast(value, jsonArray.getComponentType(), parser.getConfig());
                } else {
                    item = value;
                }
                Array.set(array, index, item);
            }
        }
    }
}
 
Example 7
Project: LineHeightEditText   File: LineHeightEditText.java   Source Code and License Vote up 5 votes
private void setTextCursorDrawable() {
    try {
        Method method = TextView.class.getDeclaredMethod("createEditorIfNeeded");
        method.setAccessible(true);
        method.invoke(this);
        Field field1 = TextView.class.getDeclaredField("mEditor");
        Field field2 = Class.forName("android.widget.Editor").getDeclaredField("mCursorDrawable");
        field1.setAccessible(true);
        field2.setAccessible(true);
        Object arr = field2.get(field1.get(this));
        Array.set(arr, 0, new LineSpaceCursorDrawable(getCursorColor(), getCursorWidth(), getCursorHeight()));
        Array.set(arr, 1, new LineSpaceCursorDrawable(getCursorColor(), getCursorWidth(), getCursorHeight()));
    } catch (Exception ignored) {
    }
}
 
Example 8
Project: lams   File: BeanWrapperImpl.java   Source Code and License Vote up 5 votes
private Object newValue(Class<?> type, String name) {
	try {
		if (type.isArray()) {
			Class<?> componentType = type.getComponentType();
			// TODO - only handles 2-dimensional arrays
			if (componentType.isArray()) {
				Object array = Array.newInstance(componentType, 1);
				Array.set(array, 0, Array.newInstance(componentType.getComponentType(), 0));
				return array;
			}
			else {
				return Array.newInstance(componentType, 0);
			}
		}
		else if (Collection.class.isAssignableFrom(type)) {
			return CollectionFactory.createCollection(type, 16);
		}
		else if (Map.class.isAssignableFrom(type)) {
			return CollectionFactory.createMap(type, 16);
		}
		else {
			return type.newInstance();
		}
	}
	catch (Exception ex) {
		// TODO Root cause exception context is lost here... should we throw another exception type that preserves context instead?
		throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + name,
				"Could not instantiate property type [" + type.getName() + "] to auto-grow nested property path: " + ex);
	}
}
 
Example 9
Project: VirtualAPK   File: DexUtil.java   Source Code and License Vote up 5 votes
private static Object combineArray(Object firstArray, Object secondArray) {
    Class<?> localClass = firstArray.getClass().getComponentType();
    int firstArrayLength = Array.getLength(firstArray);
    int allLength = firstArrayLength + Array.getLength(secondArray);
    Object result = Array.newInstance(localClass, allLength);
    for (int k = 0; k < allLength; ++k) {
        if (k < firstArrayLength) {
            Array.set(result, k, Array.get(firstArray, k));
        } else {
            Array.set(result, k, Array.get(secondArray, k - firstArrayLength));
        }
    }
    return result;
}
 
Example 10
Project: intellij-deps-ini4j   File: AbstractBeanInvocationHandler.java   Source Code and License Vote up 5 votes
protected synchronized Object getProperty(String property, Class<?> clazz)
{
    Object o;

    try
    {
        o = getPropertySpi(property, clazz);
        if (o == null)
        {
            o = zero(clazz);
        }
        else if (clazz.isArray() && (o instanceof String[]) && !clazz.equals(String[].class))
        {
            String[] str = (String[]) o;

            o = Array.newInstance(clazz.getComponentType(), str.length);
            for (int i = 0; i < str.length; i++)
            {
                Array.set(o, i, parse(str[i], clazz.getComponentType()));
            }
        }
        else if ((o instanceof String) && !clazz.equals(String.class))
        {
            o = parse((String) o, clazz);
        }
    }
    catch (Exception x)
    {
        o = zero(clazz);
    }

    return o;
}
 
Example 11
Project: parabuild-ci   File: CopyFromHelper.java   Source Code and License Vote up 5 votes
private Object doCopyArray(Object array,Class baseInterface) throws Exception {
    Class elementClass = array.getClass().getComponentType();
    int length = Array.getLength(array);
    Object newArray = Array.newInstance(elementClass,length);
    for (int i=0;i<length;i++) {
        Object element = doCopy(Array.get(array,i),baseInterface);
        Array.set(newArray,i,element);
    }
    return newArray;
}
 
Example 12
Project: heapunit   File: SimpleHeapImage.java   Source Code and License Vote up 5 votes
@Override
public Object rehydrateInstance(Instance ii) {
    ObjectArrayInstance oai = (ObjectArrayInstance) ii;
    int len = oai.getLength();
    Object a = Array.newInstance(ctype, len);
    rehydrationCache.put(ii.getInstanceId(), a);
    List<Instance> values = oai.getValues();
    for(int i = 0; i != len; ++i) {
        Array.set(a, i, rehydrate(values.get(i)));
    }
    return a;
}
 
Example 13
Project: Android-Router   File: ValueParser.java   Source Code and License Vote up 5 votes
private static void setArray(Object array, String arrayType, int index, Object value) throws ValueParseException {
    if ("int".equals(arrayType)) {
        Array.setInt(array, index, (Integer) parse(value, arrayType));
    } else if ("boolean".equals(arrayType)) {
        Array.setBoolean(array, index, (Boolean) parse(value, arrayType));
    } else if ("long".equals(arrayType)) {
        Array.setLong(array, index, (Long) parse(value, arrayType));
    } else if ("double".equals(arrayType)) {
        Array.setDouble(array, index, (Double) parse(value, arrayType));
    } else if ("float".equals(arrayType)) {
        Array.setFloat(array, index, (Float) parse(value, arrayType));
    } else {
        Array.set(array, index, parse(value, arrayType));
    }
}
 
Example 14
Project: 8R-Reflections   File: ArrayNode.java   Source Code and License Vote up 5 votes
@Override
public void setValue(Object obj, Object value, Map<String, Object> args, InstanceFactory instanceFactory) {
	Object array = obj;
	if (INTERNAL_NODE != null) {
		array = INTERNAL_NODE.getValue(obj, args);
		if (array == null) {
			Class<?> nodeClass = INTERNAL_NODE.getNodeClass(obj, args);
			array = instanceFactory.getInstance(nodeClass, args);
			INTERNAL_NODE.setValue(obj, array, args);
		}
	}
	if (array != null) {
		Array.set(array, INDEX, value);
	}
}
 
Example 15
Project: parabuild-ci   File: ArrayHolder.java   Source Code and License Vote up 5 votes
public boolean endRead() {
	setInitialized();
	array = Array.newInstance( elementClass, tempList.size() );
	for ( int i=0; i<tempList.size(); i++) {
		Array.set(array, i, tempList.get(i) );
	}
	tempList=null;
	return true;
}
 
Example 16
Project: NotifyTools   File: LazyDynaList.java   Source Code and License Vote up 4 votes
/**
 * <p>Converts the List to an Array of the specified type.</p>
 *
 * @param <T> The type of the array elements
 * @param model The model for the type of array to return
 * @return An Array of the elements in this List.
 */
@Override
public <T> T[] toArray(final T[] model) {

    final Class<?> arrayType = model.getClass().getComponentType();
    if ((DynaBean.class.isAssignableFrom(arrayType))
            || (size() == 0 && elementType == null)) {
        return super.toArray(model);
    }

    if ((arrayType.isAssignableFrom(elementType))) {
        T[] array;
        if (model.length >= size()) {
            array = model;
        } else {
            @SuppressWarnings("unchecked")
            final
            // This is safe because we know the element type
            T[] tempArray = (T[]) Array.newInstance(arrayType, size());
            array = tempArray;
        }

        for (int i = 0; i < size(); i++) {
            Object elem;
            if (Map.class.isAssignableFrom(elementType)) {
                elem = ((LazyDynaMap) get(i)).getMap();
            } else if (DynaBean.class.isAssignableFrom(elementType)) {
                elem = get(i);
            } else {
                elem = ((WrapDynaBean) get(i)).getInstance();
            }
            Array.set(array, i, elem);
        }
        return array;
    }

    throw new IllegalArgumentException("Invalid array type: "
              + arrayType.getName() + " - not compatible with '"
              + elementType.getName());

}
 
Example 17
Project: openjdk-jdk10   File: Array_set01.java   Source Code and License Vote up 4 votes
public static String test(int i, String value) {
    Array.set(array, i, value);
    return array[i];
}
 
Example 18
Project: hadoop   File: TestPBImplRecords.java   Source Code and License Vote up 4 votes
@SuppressWarnings({"rawtypes", "unchecked"})
private static Object genTypeValue(Type type) {
  Object ret = typeValueCache.get(type);
  if (ret != null) {
    return ret;
  }
  // only use positive primitive values
  if (type.equals(boolean.class)) {
    return rand.nextBoolean();
  } else if (type.equals(byte.class)) {
    return bytes[rand.nextInt(4)];
  } else if (type.equals(int.class)) {
    return rand.nextInt(1000000);
  } else if (type.equals(long.class)) {
    return Long.valueOf(rand.nextInt(1000000));
  } else if (type.equals(float.class)) {
    return rand.nextFloat();
  } else if (type.equals(double.class)) {
    return rand.nextDouble();
  } else if (type.equals(String.class)) {
    return String.format("%c%c%c",
        'a' + rand.nextInt(26),
        'a' + rand.nextInt(26),
        'a' + rand.nextInt(26));
  } else if (type instanceof Class) {
    Class clazz = (Class)type;
    if (clazz.isArray()) {
      Class compClass = clazz.getComponentType();
      if (compClass != null) {
        ret = Array.newInstance(compClass, 2);
        Array.set(ret, 0, genTypeValue(compClass));
        Array.set(ret, 1, genTypeValue(compClass));
      }
    } else if (clazz.isEnum()) {
      Object [] values = clazz.getEnumConstants();
      ret = values[rand.nextInt(values.length)];
    } else if (clazz.equals(ByteBuffer.class)) {
      // return new ByteBuffer every time
      // to prevent potential side effects
      ByteBuffer buff = ByteBuffer.allocate(4);
      rand.nextBytes(buff.array());
      return buff;
    }
  } else if (type instanceof ParameterizedType) {
    ParameterizedType pt = (ParameterizedType)type;
    Type rawType = pt.getRawType();
    Type [] params = pt.getActualTypeArguments();
    // only support EnumSet<T>, List<T>, Set<T>, Map<K,V>
    if (rawType.equals(EnumSet.class)) {
      if (params[0] instanceof Class) {
        Class c = (Class)(params[0]);
        return EnumSet.allOf(c);
      }
    } if (rawType.equals(List.class)) {
      ret = Lists.newArrayList(genTypeValue(params[0]));
    } else if (rawType.equals(Set.class)) {
      ret = Sets.newHashSet(genTypeValue(params[0]));
    } else if (rawType.equals(Map.class)) {
      Map<Object, Object> map = Maps.newHashMap();
      map.put(genTypeValue(params[0]), genTypeValue(params[1]));
      ret = map;
    }
  }
  if (ret == null) {
    throw new IllegalArgumentException("type " + type + " is not supported");
  }
  typeValueCache.put(type, ret);
  return ret;
}
 
Example 19
Project: HCFCore   File: ArrayListIterator.java   Source Code and License Vote up 3 votes
/**
 * Sets the element under the cursor.
 * <p>
 * This method sets the element that was returned by the last call
 * to {@link #next()} of {@link #previous()}.
 * <p>
 * <b>Note:</b> {@link ListIterator} implementations that support
 * <code>add()</code> and <code>remove()</code> only allow <code>set()</code> to be called
 * once per call to <code>next()</code> or <code>previous</code> (see the {@link ListIterator}
 * javadoc for more details). Since this implementation does
 * not support <code>add()</code> or <code>remove()</code>, <code>set()</code> may be
 * called as often as desired.
 *
 * @param o  the element to set
 * @throws IllegalStateException if {@link #next()} or {@link #previous()} has not been called
 * before {@link #set(Object)}
 * @see java.util.ListIterator#set
 */
public void set(final Object o) {
    if (this.lastItemIndex == -1) {
        throw new IllegalStateException("must call next() or previous() before a call to set()");
    }

    Array.set(this.array, this.lastItemIndex, o);
}
 
Example 20
Project: SimpleJSON   File: JSONSerializer.java   Source Code and License Vote up 2 votes
private static final void deserialize(Class<?> clazz, Object classObject, Object targetObject, JSONArray json) throws Exception {

		Class<?> type = targetObject.getClass().getComponentType();
		
		for(int index = 0; index < json.size(); index++) {
			
			Object value = json.get(index);
			
			if(float.class.isAssignableFrom(type) || Float.class.isAssignableFrom(type)) {
				
				Array.set(targetObject, index, ((Number)value).floatValue());
				
			} else if(double.class.isAssignableFrom(type) || Double.class.isAssignableFrom(type)) {
				
				Array.set(targetObject, index, ((Number)value).doubleValue());
				
			} else if(byte.class.isAssignableFrom(type) || Byte.class.isAssignableFrom(type)) {
				
				Array.set(targetObject, index, ((Number)value).byteValue());
				
			} else if(short.class.isAssignableFrom(type) || Short.class.isAssignableFrom(type)) {
				
				Array.set(targetObject, index, ((Number)value).shortValue());
				
			} else if(int.class.isAssignableFrom(type) || Integer.class.isAssignableFrom(type)) {
				
				Array.set(targetObject, index, ((Number)value).intValue());
				
			} else if(long.class.isAssignableFrom(type) || Long.class.isAssignableFrom(type)) {
				
				Array.set(targetObject, index, ((Number)value).longValue());
				
			} else if(String.class.isAssignableFrom(type) || Number.class.isAssignableFrom(type) || Boolean.class.isAssignableFrom(type) || boolean.class.isAssignableFrom(type)) {
	
				Array.set(targetObject, index, value);
				
			} else if(Enum.class.isAssignableFrom(type)) {
				
				for(Object constant : type.getEnumConstants()) {
					
					if(((Enum<?>)constant).name().equals(value.toString())) {
						
						Array.set(targetObject, index, constant);
						break;
					}
				}
				
			} else if(type.getAnnotation(JSONRoot.class) != null) {
				
				Object newObject = type.newInstance();
				JSONSerializer.deserialize((JSONObject)value, newObject);
				Array.set(targetObject, index, newObject);
				
			} else if(Map.class.isAssignableFrom(type)) {
				
				@SuppressWarnings("unchecked")
				Map<Object, Object> map = (Map<Object, Object>)type.newInstance();
				JSONSerializer.deserialize(clazz, classObject, map, (JSONObject)value);
				Array.set(targetObject, index, map);
				
			} else if(Collection.class.isAssignableFrom(type)) {
				
				@SuppressWarnings("unchecked")
				Collection<Object> collection = (Collection<Object>)type.newInstance();
				JSONSerializer.deserialize(clazz, classObject, collection, (JSONArray)value);
				Array.set(targetObject, index, collection);
				
			} else if(type.isArray()) {
				
				Object newArray = Array.newInstance(type.getComponentType(), ((JSONArray)value).size());
				JSONSerializer.deserialize(clazz, classObject, newArray, ((JSONArray)value));
				Array.set(targetObject, index, newArray);
				
			} else if(JSONTypeSerializationHandler.class.isAssignableFrom(clazz)) {
				
				Array.set(targetObject, index, ((JSONTypeSerializationHandler)classObject).deserialize(type, value));
			}
		}
	}