List of usage examples for java.lang.reflect Array newInstance
public static Object newInstance(Class<?> componentType, int... dimensions) throws IllegalArgumentException, NegativeArraySizeException
From source file:hivemall.utils.lang.ArrayUtils.java
@Nullable public static Object[] subarray(@Nullable final Object[] array, int startIndexInclusive, int endIndexExclusive) { if (array == null) { return null; }// w w w . j ava 2s .co m if (startIndexInclusive < 0) { startIndexInclusive = 0; } if (endIndexExclusive > array.length) { endIndexExclusive = array.length; } int newSize = endIndexExclusive - startIndexInclusive; Class<?> type = array.getClass().getComponentType(); if (newSize <= 0) { return (Object[]) Array.newInstance(type, 0); } Object[] subarray = (Object[]) Array.newInstance(type, newSize); System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); return subarray; }
From source file:com.browseengine.bobo.serialize.JSONSerializer.java
public static JSONSerializable deSerialize(Class clz, JSONObject jsonObj) throws JSONSerializationException, JSONException { Iterator iter = jsonObj.keys(); if (!JSONSerializable.class.isAssignableFrom(clz)) { throw new JSONSerializationException(clz + " is not an instance of " + JSONSerializable.class); }/*from w w w. ja v a 2 s .c o m*/ JSONSerializable retObj; try { retObj = (JSONSerializable) clz.newInstance(); } catch (Exception e1) { throw new JSONSerializationException( "trouble with no-arg instantiation of " + clz.toString() + ": " + e1.getMessage(), e1); } if (JSONExternalizable.class.isAssignableFrom(clz)) { ((JSONExternalizable) retObj).fromJSON(jsonObj); return retObj; } while (iter.hasNext()) { String key = (String) iter.next(); try { Field f = clz.getDeclaredField(key); if (f != null) { f.setAccessible(true); Class type = f.getType(); if (type.isArray()) { JSONArray array = jsonObj.getJSONArray(key); int len = array.length(); Class cls = type.getComponentType(); Object newArray = Array.newInstance(cls, len); for (int k = 0; k < len; ++k) { loadObject(newArray, cls, k, array); } f.set(retObj, newArray); } else { loadObject(retObj, f, jsonObj); } } } catch (Exception e) { throw new JSONSerializationException(e.getMessage(), e); } } return retObj; }
From source file:com.trafficspaces.api.model.Resource.java
public void setJSONObject(JSONObject jsonObject) { Iterator itr = jsonObject.keys(); while (itr.hasNext()) { String key = (String) itr.next(); Object value = jsonObject.opt(key); try {/*from w ww . j av a 2 s . c om*/ Field field = this.getClass().getField(key); Class type = field.getType(); int fieldModifiers = field.getModifiers(); //System.out.println("key=" + key + ", name=" + field.getName() + ", value=" + value + ", type=" +type + ", componentType=" +type.getComponentType() + // ", ispublic="+Modifier.isPublic(fieldModifiers) + ", isstatic="+Modifier.isStatic(fieldModifiers) + ", isnative="+Modifier.isNative(fieldModifiers) + // ", isprimitive="+type.isPrimitive() + ", isarray="+type.isArray() + ", isResource="+Resource.class.isAssignableFrom(type)); if (type.isPrimitive()) { if (type.equals(int.class)) { field.setInt(this, jsonObject.getInt(key)); } else if (type.equals(double.class)) { field.setDouble(this, jsonObject.getDouble(key)); } } else if (type.isArray()) { JSONArray jsonArray = null; if (value instanceof JSONArray) { jsonArray = (JSONArray) value; } else if (value instanceof JSONObject) { JSONObject jsonSubObject = (JSONObject) value; jsonArray = jsonSubObject.optJSONArray(key.substring(0, key.length() - 1)); } if (jsonArray != null && jsonArray.length() > 0) { Class componentType = type.getComponentType(); Object[] values = (Object[]) Array.newInstance(componentType, jsonArray.length()); for (int j = 0; j < jsonArray.length(); j++) { Resource resource = (Resource) componentType.newInstance(); resource.setJSONObject(jsonArray.getJSONObject(j)); values[j] = resource; } field.set(this, values); } } else if (Resource.class.isAssignableFrom(type) && value instanceof JSONObject) { Resource resource = (Resource) type.newInstance(); resource.setJSONObject((JSONObject) value); field.set(this, resource); } else if (type.equals(String.class) && value instanceof String) { field.set(this, (String) value); } } catch (NoSuchFieldException nsfe) { System.err.println("warning: field does not exist. key=" + key + ",value=" + value); } catch (Exception e) { e.printStackTrace(); System.err.println("error: key=" + key + ",value=" + value + ", error=" + e.getMessage()); } } }
From source file:ArrayMap.java
/** * Removes the specified object from the array * /*from ww w .ja v a2 s . com*/ * @param <T> * The type of the array * @param anArray * The array to remove an element from * @param anIndex * The index of the element to remove * @return A new array with all the elements of <code>anArray</code> except * the element at <code>anIndex</code> */ public static <T> T[] remove(T[] anArray, int anIndex) { T[] ret; if (anArray == null) return null; else { ret = (T[]) Array.newInstance(anArray.getClass().getComponentType(), anArray.length - 1); } System.arraycopy(anArray, 0, ret, 0, anIndex); System.arraycopy(anArray, anIndex + 1, ret, anIndex, anArray.length - anIndex - 1); return ret; }
From source file:com.opengamma.analytics.math.curve.ObjectsCurve.java
/** * // w w w . j a v a 2s. com * @param data A map of <i>x-y</i> data, not null * @param isSorted Is the <i>x</i>-data sorted * @param name The name of the curve */ public ObjectsCurve(final Map<T, U> data, final boolean isSorted, final String name) { super(name); ArgumentChecker.noNulls(data.keySet(), "x values"); ArgumentChecker.noNulls(data.values(), "y values"); _n = data.size(); final Map.Entry<T, U> firstEntry = data.entrySet().iterator().next(); _xData = data.keySet().toArray((T[]) Array.newInstance(firstEntry.getKey().getClass(), 0)); _yData = data.values().toArray((U[]) Array.newInstance(firstEntry.getValue().getClass(), 0)); if (!isSorted) { ParallelArrayBinarySort.parallelBinarySort(_xData, _yData); } }
From source file:org.zlogic.vogon.web.TomcatConfigurer.java
/** * Configures SSL for Tomcat container/*from w ww. j a v a 2s . co m*/ * * @param container ConfigurableEmbeddedServletContainer instance to * configure */ private void configureSSL(ConfigurableEmbeddedServletContainer container) { if (serverTypeDetector.getKeystoreFile().isEmpty() || serverTypeDetector.getKeystorePassword().isEmpty()) { log.debug(messages.getString("KEYSTORE_FILE_OR_PASSWORD_NOT_DEFINED")); return; } log.info(MessageFormat.format(messages.getString("USING_KEYSTORE_WITH_PASSWORD"), new Object[] { serverTypeDetector.getKeystoreFile(), serverTypeDetector.getKeystorePassword().replaceAll(".{1}", "*") })); //NOI18N Object connector; Class connectorClass = null; try { log.debug(messages.getString("CONFIGURING_CONNECTOR")); connectorClass = getClass().getClassLoader().loadClass("org.apache.catalina.connector.Connector"); //NOI18N connector = connectorClass.newInstance(); connectorClass.getMethod("setPort", Integer.TYPE).invoke(connector, 8443); //NOI18N connectorClass.getMethod("setSecure", Boolean.TYPE).invoke(connector, true); //NOI18N connectorClass.getMethod("setScheme", String.class).invoke(connector, "https"); //NOI18N connectorClass.getMethod("setURIEncoding", String.class).invoke(connector, utf8Charset.name()); //NOI18N } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException ex) { throw new RuntimeException(messages.getString("CANNOT_CONFIGURE_CONNECTOR"), ex); } Object proto; try { log.debug(messages.getString("CONFIGURING_PROTOCOLHANDLER_PARAMETERS")); proto = connectorClass.getMethod("getProtocolHandler").invoke(connector); //NOI18N Class protoClass = proto.getClass(); log.debug(java.text.MessageFormat.format(messages.getString("CONFIGURING_PROTOCOLHANDLER_CLASS"), new Object[] { protoClass.getCanonicalName() })); protoClass.getMethod("setSSLEnabled", Boolean.TYPE).invoke(proto, true); //NOI18N protoClass.getMethod("setKeystorePass", String.class).invoke(proto, serverTypeDetector.getKeystorePassword()); //NOI18N protoClass.getMethod("setKeystoreType", String.class).invoke(proto, "JKS"); //NOI18N protoClass.getMethod("setKeyAlias", String.class).invoke(proto, "vogonkey"); //NOI18N protoClass.getMethod("setKeystoreFile", String.class).invoke(proto, new File(serverTypeDetector.getKeystoreFile()).getAbsolutePath()); //NOI18N } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { throw new RuntimeException(messages.getString("CANNOT_CONFIGURE_PROTOCOLHANDLER"), ex); } try { log.debug(messages.getString("ADDING_CONNECTOR_TO_TOMCATEMBEDDEDSERVLETCONTAINERFACTORY")); Object connectors = Array.newInstance(connectorClass, 1); Array.set(connectors, 0, connector); container.getClass().getMethod("addAdditionalTomcatConnectors", connectors.getClass()).invoke(container, connectors); //NOI18N } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { throw new RuntimeException( messages.getString("CANNOT_ADD_CONNECTOR_TO_TOMCATEMBEDDEDSERVLETCONTAINERFACTORY"), ex); } }
From source file:io.github.pellse.decorator.util.reflection.ReflectionUtils.java
@SuppressWarnings("unchecked") public static <T> T[] insert(T[] objArray, int index, T obj) { if (index > -1) { List<T> list = new ArrayList<>(Arrays.asList(objArray)); list.add(index, obj);/*ww w. ja v a2s .c om*/ return list.toArray((T[]) Array.newInstance(objArray.getClass().getComponentType(), 0)); } return objArray; }
From source file:com.hortonworks.hbase.replication.bridge.WritableRpcEngine.java
/** Expert: Make multiple, parallel calls to a set of servers. */ @Override//from www . j ava 2 s. c om public Object[] call(Method method, Object[][] params, InetSocketAddress[] addrs, Class<? extends VersionedProtocol> protocol, User ticket, Configuration conf) throws IOException, InterruptedException { if (this.client == null) { throw new IOException("Client must be initialized by calling setConf(Configuration)"); } Invocation[] invocations = new Invocation[params.length]; for (int i = 0; i < params.length; i++) { invocations[i] = new Invocation(method, protocol, params[i]); } Writable[] wrappedValues = client.call(invocations, addrs, protocol, ticket); if (method.getReturnType() == Void.TYPE) { return null; } Object[] values = (Object[]) Array.newInstance(method.getReturnType(), wrappedValues.length); for (int i = 0; i < values.length; i++) { if (wrappedValues[i] != null) { values[i] = ((HbaseObjectWritable) wrappedValues[i]).get(); } } return values; }
From source file:jp.go.nict.langrid.client.soap.io.SoapResponseParser.java
private static <T> T nodeToType(XPathWorkspace w, Node node, Class<T> clazz, Converter converter) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ConversionException, DOMException, ParseException { if (clazz.isPrimitive()) { return converter.convert(resolveHref(w, node).getTextContent(), clazz); } else if (clazz.equals(String.class)) { return clazz.cast(resolveHref(w, node).getTextContent()); } else if (clazz.equals(byte[].class)) { try {//from w ww . ja v a2 s .c om return clazz.cast(Base64.decodeBase64(resolveHref(w, node).getTextContent().getBytes("ISO8859-1"))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } else if (clazz.equals(Calendar.class)) { Date date = fmt.get().parse(resolveHref(w, node).getTextContent()); Calendar c = Calendar.getInstance(); c.setTime(date); return clazz.cast(c); } else if (clazz.isArray()) { Class<?> ct = clazz.getComponentType(); List<Object> elements = new ArrayList<Object>(); node = resolveHref(w, node); for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) { if (!(child instanceof Element)) continue; elements.add(nodeToType(w, child, ct, converter)); } return clazz.cast(elements.toArray((Object[]) Array.newInstance(ct, elements.size()))); } else { T instance = clazz.newInstance(); node = resolveHref(w, node); for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) { if (!(child instanceof Element)) continue; String nn = child.getLocalName(); Method setter = ClassUtil.findSetter(clazz, nn); setter.invoke(instance, nodeToType(w, resolveHref(w, child), setter.getParameterTypes()[0], converter)); } return instance; } }
From source file:com.comcast.cereal.engines.AbstractCerealEngine.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public <T> T deCerealize(Object cereal, Class<T> clazz) throws CerealException { ObjectCache objectCache = new ObjectCache(settings); try {//from w w w . ja v a 2 s .c om if (cereal instanceof List && clazz.isArray()) { List<Object> cerealList = (List) cereal; Class arrayType = clazz.getComponentType(); Cerealizer cerealizer = cerealFactory.getCerealizer(arrayType); T array = (T) Array.newInstance(arrayType, cerealList.size()); for (int i = 0; i < cerealList.size(); i++) { Array.set(array, i, cerealizer.deCerealize(cerealList.get(i), objectCache)); } return array; } else { Class<?> runtimeClass = cerealFactory.getRuntimeClass(cereal); Cerealizer cerealizer = cerealFactory.getCerealizer(clazz); if ((runtimeClass != null) && clazz.isAssignableFrom(runtimeClass)) { /** need to check if the runtime class is a subclass of the given class * or we will get a class cast exception when we return it */ cerealizer = cerealFactory.getRuntimeCerealizer(cereal, cerealizer); } return (T) cerealizer.deCerealize(cereal, objectCache); } } finally { objectCache.resetCache(); } }