List of usage examples for java.lang.reflect Array get
public static native Object get(Object array, int index) throws IllegalArgumentException, ArrayIndexOutOfBoundsException;
From source file:javadz.beanutils.ConvertUtilsBean.java
/** * Convert the specified value into a String. If the specified value * is an array, the first element (converted to a String) will be * returned. The registered {@link Converter} for the * <code>java.lang.String</code> class will be used, which allows * applications to customize Object->String conversions (the default * implementation simply uses toString()). * * @param value Value to be converted (may be null) * @return The converted String value/* ww w . j a v a 2 s. co m*/ */ public String convert(Object value) { if (value == null) { return null; } else if (value.getClass().isArray()) { if (Array.getLength(value) < 1) { return (null); } value = Array.get(value, 0); if (value == null) { return null; } else { Converter converter = lookup(String.class); return ((String) converter.convert(String.class, value)); } } else { Converter converter = lookup(String.class); return ((String) converter.convert(String.class, value)); } }
From source file:com.krawler.br.exp.Variable.java
private void removeIndexedElement(Object cont, int index) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, ProcessException { if (cont == null) { throw new ProcessException("container not found for variable: " + this); } else {//from w ww. ja v a 2s .c o m if (indices != null && indices.containsKey(index)) { Iterator<Expression> itr = indices.get(index).iterator(); Object container = null; while (cont != null && itr.hasNext()) { container = cont; int idx = ((Number) itr.next().getValue()).intValue(); if (itr.hasNext()) { if (cont instanceof JSONArray) { cont = ((JSONArray) cont).opt(idx); } else if (cont instanceof java.util.List) { cont = ((java.util.List) cont).get(idx); } else if (cont.getClass().isArray()) { cont = Array.get(cont, idx); } else throw new ProcessException("Unsuported container type found in variable: " + this); } else { if (container == null) throw new ProcessException("container not found for variable: " + this); else if (container instanceof JSONArray) { JSONArray jArr = (JSONArray) container; jArr.remove(index); } else if (container instanceof java.util.List) { java.util.List list = (java.util.List) container; list.remove(index); } else { throw new ProcessException("Remove not supported on " + container.getClass().getName()); } break; } } } } }
From source file:com.jaspersoft.jasperserver.ws.axis2.scheduling.ReportJobBeanTraslator.java
protected Object toCollectionValue(Class parameterType, Object valueArray) { Object reportValue;// w w w . j a v a 2 s. co m int valueCount = Array.getLength(valueArray); if (parameterType.equals(Object.class) || parameterType.equals(Collection.class) || parameterType.equals(Set.class)) { Collection values = new ListOrderedSet(); for (int i = 0; i < valueCount; ++i) { values.add(Array.get(valueArray, i)); } reportValue = values; } else if (parameterType.equals(List.class)) { Collection values = new ArrayList(valueCount); for (int i = 0; i < valueCount; ++i) { values.add(Array.get(valueArray, i)); } reportValue = values; } else if (parameterType.isArray()) { Class componentType = parameterType.getComponentType(); if (componentType.equals(valueArray.getClass().getComponentType())) { reportValue = valueArray; } else { reportValue = Array.newInstance(componentType, valueCount); for (int i = 0; i < valueCount; ++i) { Array.set(reportValue, i, Array.get(valueArray, i)); } } } else { throw new JSException("report.scheduling.ws.collection.parameter.type.not.supported", new Object[] { parameterType.getName() }); } return reportValue; }
From source file:com.xpfriend.fixture.cast.temp.ObjectValidatorBase.java
protected String fromArrayToString(Object array) { StringBuilder sb = new StringBuilder(); int length = Array.getLength(array); for (int i = 0; i < length; i++) { if (i != 0) { sb.append('|'); }/*from w w w . jav a 2s .c om*/ sb.append(toString(Array.get(array, i))); } return sb.toString(); }
From source file:com.twinsoft.convertigo.beans.core.TransactionWithVariables.java
public Object getParameterValue(String parameterName) throws EngineException { Object variableValue = null;/*from w w w. jav a 2 s .c om*/ int variableVisibility = getVariableVisibility(parameterName); // Transaction parameter variableValue = variables.get(parameterName); if (variableValue != null) Engine.logBeans.trace("(TransactionWithVariables) parameter value: " + Visibility.Logs.printValue(variableVisibility, variableValue)); // Otherwise context parameter if (variableValue == null && context != null) { variableValue = (context.get(parameterName) == null ? null : context.get(parameterName)); if (variableValue != null) Engine.logBeans.trace("(TransactionWithVariables) context value: " + Visibility.Logs.printValue(variableVisibility, variableValue)); } // Otherwise default transaction parameter value if (variableValue == null) { variableValue = getVariableValue(parameterName); if (variableValue != null) Engine.logBeans.trace("(TransactionWithVariables) default value: " + Visibility.Logs.printValue(variableVisibility, variableValue)); } if (variableValue == null) { Engine.logBeans.trace("(TransactionWithVariables) none value found"); } else if (variableValue.getClass().isArray()) { Engine.logBeans.trace("(TransactionWithVariables) transform the array value as a collection"); if (variableValue.getClass().getComponentType().isPrimitive()) { int len = Array.getLength(variableValue); Collection<Object> newVariableValue = new ArrayList<Object>(len); for (int i = 0; i < len; i++) { newVariableValue.add(Array.get(variableValue, i)); } variableValue = newVariableValue; } else { variableValue = Arrays.asList((Object[]) variableValue); } } return variableValue; }
From source file:com.twinsoft.convertigo.engine.util.XMLUtils.java
public static Node writeObjectToXml(Document document, Object object, Object compiledValue) throws Exception { if (object == null) return null; if (object instanceof Enum) { object = ((Enum<?>) object).name(); }/* w ww .ja v a 2 s .co m*/ // Simple objects if ((object instanceof Boolean) || (object instanceof Integer) || (object instanceof Double) || (object instanceof Float) || (object instanceof Character) || (object instanceof Long) || (object instanceof Short) || (object instanceof Byte)) { Element element = document.createElement(object.getClass().getName()); element.setAttribute("value", object.toString()); if (compiledValue != null) element.setAttribute("compiledValue", compiledValue.toString()); return element; } // Strings else if (object instanceof String) { Element element = document.createElement(object.getClass().getName()); element.setAttribute("value", object.toString()); if (compiledValue != null) { element.setAttribute("compiledValueClass", compiledValue.getClass().getCanonicalName()); element.setAttribute("compiledValue", compiledValue.toString()); } return element; } // Arrays else if (object.getClass().getName().startsWith("[")) { String arrayClassName = object.getClass().getName(); int i = arrayClassName.lastIndexOf('['); String itemClassName = arrayClassName.substring(i + 1); char c = itemClassName.charAt(itemClassName.length() - 1); switch (c) { case ';': itemClassName = itemClassName.substring(1, itemClassName.length() - 1); break; case 'B': itemClassName = "byte"; break; case 'C': itemClassName = "char"; break; case 'D': itemClassName = "double"; break; case 'F': itemClassName = "float"; break; case 'I': itemClassName = "int"; break; case 'J': itemClassName = "long"; break; case 'S': itemClassName = "short"; break; case 'Z': itemClassName = "boolean"; break; } Element element = document.createElement("array"); element.setAttribute("classname", itemClassName); int len = Array.getLength(object); element.setAttribute("length", Integer.toString(len)); Node subNode; for (int k = 0; k < len; k++) { subNode = writeObjectToXml(document, Array.get(object, k)); if (subNode != null) { element.appendChild(subNode); } } return element; } // XMLization else if (object instanceof XMLizable) { Element element = document.createElement("xmlizable"); element.setAttribute("classname", object.getClass().getName()); element.appendChild(((XMLizable) object).writeXml(document)); return element; } // Default serialization else { Element element = document.createElement("serializable"); element.setAttribute("classname", object.getClass().getName()); String objectBytesEncoded = null; byte[] objectBytes = null; // We write the object to a bytes array ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); objectOutputStream.writeObject(object); objectOutputStream.flush(); outputStream.close(); // Now, we retrieve the object bytes objectBytes = outputStream.toByteArray(); objectBytesEncoded = org.apache.commons.codec.binary.Base64.encodeBase64String(objectBytes); CDATASection cDATASection = document.createCDATASection(new String(objectBytesEncoded)); element.appendChild(cDATASection); return element; } }
From source file:jef.tools.collection.CollectionUtils.java
/** * Enumation?Collection//from w ww . j a v a 2 s . c om * * @param data * @param type * @return */ @SuppressWarnings("unchecked") public static <T> Collection<T> toCollection(Object data, Class<T> type) { if (data == null) return null; if (data instanceof Collection) { return ((Collection<T>) data); } else if (data.getClass().isArray()) { if (data.getClass().getComponentType().isPrimitive()) { int len = Array.getLength(data); List<T> result = new ArrayList<T>(len); for (int i = 0; i < len; i++) { result.add((T) Array.get(data, i)); } } else { return Arrays.asList((T[]) data); } } else if (data instanceof Enumeration) { Enumeration<T> e = (Enumeration<T>) data; List<T> result = new ArrayList<T>(); for (; e.hasMoreElements();) { result.add(e.nextElement()); } return result; } throw new IllegalArgumentException("The input type " + data.getClass() + " can not convert to Collection."); }
From source file:com.astamuse.asta4d.web.form.flow.base.AbstractFormFlowSnippet.java
/** * Sub classes could override this method to customize how to handle the injection trace data for type unmatch errors. * //from w w w .j a va 2s . com * @param fieldName * @param fieldDataType * @param rawTraceData * @return */ protected Object convertRawInjectionTraceDataToRenderingData(String fieldName, Class fieldDataType, Object rawTraceData) { if (fieldDataType.isArray() && rawTraceData.getClass().isArray()) { return rawTraceData; } else if (rawTraceData.getClass().isArray()) {// but field data type is // not array if (Array.getLength(rawTraceData) > 0) { return Array.get(rawTraceData, 0); } else { return null; } } else { return rawTraceData; } }
From source file:org.evosuite.regression.ObjectFields.java
private static Map<String, Object> getAllVars(Object p, int counter, String prefix) { // TODO Auto-generated method stub // logger.warn("getting: " + ((p instanceof Field)?((Field) // p).getType():p.getClass()) + ", count:" + counter); Map<String, Object> values = new HashMap<String, Object>(); // if(((p instanceof Field)?((Field) p).getType():p.getClass()) == null) // return values; if (p == null) return values; Collection<Field> fields = getAllFields(p.getClass()); for (Field field : fields) { // String what_happened = ""; GenericClass gc = new GenericClass(field.getType()); if (ClassUtils.isPrimitiveOrWrapper(field.getType()) || gc.isString()) { // what_happened += ", " + field.getType() + " is primitive,"; if (field.getName().equals("serialVersionUID")) continue; values.put(prefix + field.getName(), getObjectValue(getFieldValue(field, p))); } else if (field.getType().equals(Object.class) || counter >= MAX_RECURSION) { values.put(prefix + field.getName(), (getObjectValue(getFieldValue(field, p)) != null)); // what_happened += ", " + field.getType() + ",reached end,"; } else if (field.getType().isArray()) { /*/*from ww w .ja v a2s.c om*/ * values.put(prefix + field.getName(), Array * .getLength(getObjectValue(getFieldValue(field, p)))); */ // Object[] arr = (Object[]) getFieldValue(field, p); /* * for(Object o: arr){ values.putAll(getAllVars(o, counter + * 1,prefix + ((prefix.equals(""))?"":".")+field.getName())); } */ Object arr = getFieldValue(field, p); if (arr == null) return values; for (int n = 0; n < Array.getLength(arr); n++) { // values.putAll(getAllVars(Array.get(arr,n), counter + // 1,prefix + ((prefix.isEmpty())?"":".")+field.getName())); values.put(prefix + field.getName(), getAllVars(Array.get(arr, n), counter + 1, prefix + ((prefix.isEmpty()) ? "" : ".") + field.getName())); } } else { try { field.setAccessible(true); // values.putAll(getAllVars(field.get(p), counter + 1,prefix // + ((prefix.isEmpty())?"":".")+field.getName())); values.put(prefix + field.getName(), getAllVars(field.get(p), counter + 1, prefix + ((prefix.isEmpty()) ? "" : ".") + field.getName())); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block return values; } catch (IllegalAccessException e) { // TODO Auto-generated catch block return values; } // what_happened += ", " + field.getType() + ",recursed,"; } // logger.warn(prefix + field.getName() + what_happened); } /* * if (ClassUtils.isPrimitiveOrWrapper(p.getClass())){ * * return null; } else { * * } */ return values; }
From source file:org.janusgraph.graphdb.serializer.SerializerTest.java
License:asdf
@Test public void testSerializationMixture() { serialize.registerClass(1, TClass1.class, new TClass1Serializer()); for (int t = 0; t < 1000; t++) { DataOutput out = serialize.getDataOutput(128); int num = random.nextInt(100) + 1; final List<SerialEntry> entries = new ArrayList<>(num); for (int i = 0; i < num; i++) { Map.Entry<Class, Factory> type = Iterables.get(TYPES.entrySet(), random.nextInt(TYPES.size())); Object element = type.getValue().newInstance(); boolean notNull = true; if (random.nextDouble() < 0.5) { notNull = false;/* w w w. j a v a2 s .c o m*/ if (random.nextDouble() < 0.2) element = null; } entries.add(new SerialEntry(element, type.getKey(), notNull)); if (notNull) out.writeObjectNotNull(element); else out.writeObject(element, type.getKey()); } StaticBuffer sb = out.getStaticBuffer(); ReadBuffer in = sb.asReadBuffer(); for (SerialEntry entry : entries) { Object read; if (entry.notNull) read = serialize.readObjectNotNull(in, entry.clazz); else read = serialize.readObject(in, entry.clazz); if (entry.object == null) assertNull(read); else if (entry.clazz.isArray()) { assertEquals(Array.getLength(entry.object), Array.getLength(read)); for (int i = 0; i < Array.getLength(read); i++) { assertEquals(Array.get(entry.object, i), Array.get(read, i)); } } else assertEquals(entry.object, read); } } }