List of usage examples for java.lang.reflect Array newInstance
public static Object newInstance(Class<?> componentType, int... dimensions) throws IllegalArgumentException, NegativeArraySizeException
From source file:org.guicerecipes.spring.support.AutowiredMemberProvider.java
protected Object provideArrayValue(Member member, TypeLiteral<?> type, Class<?> memberType, Predicate<Binding> filter) { Class<?> componentType = memberType.getComponentType(); Set<Binding<?>> set = getSortedBindings(componentType, filter); // TODO should we return an empty array when no matches? // FWIW Spring seems to return null if (set.isEmpty()) { return null; }/*from w w w . j a v a 2 s . c o m*/ Object array = Array.newInstance(componentType, set.size()); int index = 0; for (Binding<?> binding : set) { Object value = binding.getProvider().get(); Array.set(array, index++, value); } return array; }
From source file:org.crazydog.util.spring.ObjectUtils.java
/** * Convert the given array (which may be a primitive array) to an * object array (if necessary of primitive wrapper objects). * <p>A {@code null} source value will be converted to an * empty Object array.//from www . j a va 2 s .c om * @param source the (potentially primitive) array * @return the corresponding object array (never {@code null}) * @throws IllegalArgumentException if the parameter is not an array */ public static Object[] toObjectArray(Object source) { if (source instanceof Object[]) { return (Object[]) source; } if (source == null) { return new Object[0]; } if (!source.getClass().isArray()) { throw new IllegalArgumentException("Source is not an array: " + source); } int length = Array.getLength(source); if (length == 0) { return new Object[0]; } Class<?> wrapperType = Array.get(source, 0).getClass(); Object[] newArray = (Object[]) Array.newInstance(wrapperType, length); for (int i = 0; i < length; i++) { newArray[i] = Array.get(source, i); } return newArray; }
From source file:org.nabucco.alfresco.enhScriptEnv.common.script.converter.rhino.NativeArrayConverter.java
/** * {@inheritDoc}/*from w w w . j a v a 2s . c om*/ */ @Override public Object convertValueForJava(final Object value, final ValueConverter globalDelegate, final Class<?> expectedClass) { if (!(value instanceof NativeArray)) { throw new IllegalArgumentException("value must be a NativeArray"); } final NativeArray arr = (NativeArray) value; final Object[] ids = arr.getIds(); final Object result; if (expectedClass.isAssignableFrom(List.class) || expectedClass.isArray()) { final Class<?> expectedComponentClass = expectedClass.isArray() ? expectedClass.getComponentType() : Object.class; final List<Object> list = new ArrayList<Object>(); for (int idx = 0; idx < ids.length; idx++) { if (ids[idx] instanceof Integer) { final Object element = arr.get(((Integer) ids[idx]).intValue(), arr); final Object converted = globalDelegate.convertValueForJava(element, expectedComponentClass); list.add(converted); } } if (expectedClass.isArray()) { final Object newArr = Array.newInstance(expectedComponentClass, list.size()); for (int idx = 0; idx < list.size(); idx++) { Array.set(newArr, idx, list.get(idx)); } result = newArr; } else { result = list; } } else { final Map<Object, Object> propValues = new HashMap<Object, Object>(ids.length); for (final Object propId : ids) { final Object val = arr.get(propId.toString(), arr); final Object convertedKey = globalDelegate.convertValueForJava(propId); final Object convertedValue = globalDelegate.convertValueForJava(val); propValues.put(convertedKey, convertedValue); } result = propValues; } return result; }
From source file:io.github.wysohn.triggerreactor.tools.ReflectionUtil.java
@SuppressWarnings({ "unchecked", "unchecked" }) public static Object invokeMethod(Class<?> clazz, Object obj, String methodName, Object... args) throws NoSuchMethodException, IllegalArgumentException, InvocationTargetException, IllegalAccessException {/* w ww . java 2 s . c om*/ try { List<Method> validMethods = new ArrayList<>(); for (Method method : clazz.getMethods()) { Class<?>[] parameterTypes = null; if (!method.getName().equals(methodName)) { continue; } parameterTypes = method.getParameterTypes(); if (method.isVarArgs()) { if (method.isVarArgs() && (parameterTypes.length - args.length >= 2)) { parameterTypes = null; continue; } } else { if (parameterTypes.length != args.length) { parameterTypes = null; continue; } } if (method.isVarArgs()) { boolean matches = false; // check non vararg part for (int i = 0; i < parameterTypes.length - 1; i++) { matches = checkMatch(parameterTypes[i], args[i]); if (!matches) break; } // check rest for (int i = parameterTypes.length - 1; i < args.length; i++) { Class<?> arrayType = parameterTypes[parameterTypes.length - 1].getComponentType(); matches = checkMatch(arrayType, args[i]); if (!matches) break; } if (matches) { validMethods.add(method); } } else { boolean matches = true; for (int i = 0; i < parameterTypes.length; i++) { matches = checkMatch(parameterTypes[i], args[i]); if (!matches) break; } if (matches) { validMethods.add(method); } } } if (!validMethods.isEmpty()) { Method method = validMethods.get(0); for (int i = 1; i < validMethods.size(); i++) { Method targetMethod = validMethods.get(i); Class<?>[] currentParams = method.getParameterTypes(); Class<?>[] targetParams = targetMethod.getParameterTypes(); if (method.isVarArgs() && targetMethod.isVarArgs()) { for (int j = 0; j < currentParams.length; j++) { if (currentParams[j].isAssignableFrom(targetParams[j])) { method = targetMethod; break; } } } else if (method.isVarArgs()) { //usually, non-vararg is more specific method. So we use that method = targetMethod; } else if (targetMethod.isVarArgs()) { //do nothing } else { for (int j = 0; j < currentParams.length; j++) { if (targetParams[j].isEnum()) { // enum will be handled later method = targetMethod; break; } else if (ClassUtils.isAssignable(targetParams[j], currentParams[j], true)) { //narrow down to find the most specific method method = targetMethod; break; } } } } method.setAccessible(true); for (int i = 0; i < args.length; i++) { Class<?>[] parameterTypes = method.getParameterTypes(); if (args[i] instanceof String && i < parameterTypes.length && parameterTypes[i].isEnum()) { try { args[i] = Enum.valueOf((Class<? extends Enum>) parameterTypes[i], (String) args[i]); } catch (IllegalArgumentException ex1) { // Some overloaded methods already has // String to Enum conversion // So just lets see if one exists Class<?>[] types = new Class<?>[args.length]; for (int k = 0; k < args.length; k++) types[k] = args[k].getClass(); try { Method alternative = clazz.getMethod(methodName, types); return alternative.invoke(obj, args); } catch (NoSuchMethodException ex2) { throw new RuntimeException( "Tried to convert value [" + args[i] + "] to Enum [" + parameterTypes[i] + "] or find appropriate method but found nothing. Make sure" + " that the value [" + args[i] + "] matches exactly with one of the Enums in [" + parameterTypes[i] + "] or the method you are looking exists."); } } } } if (method.isVarArgs()) { Class<?>[] parameterTypes = method.getParameterTypes(); Object varargs = Array.newInstance(parameterTypes[parameterTypes.length - 1].getComponentType(), args.length - parameterTypes.length + 1); for (int k = 0; k < Array.getLength(varargs); k++) { Array.set(varargs, k, args[parameterTypes.length - 1 + k]); } Object[] newArgs = new Object[parameterTypes.length]; for (int k = 0; k < newArgs.length - 1; k++) { newArgs[k] = args[k]; } newArgs[newArgs.length - 1] = varargs; args = newArgs; } return method.invoke(obj, args); } if (args.length > 0) { StringBuilder builder = new StringBuilder(String.valueOf(args[0].getClass().getSimpleName())); for (int i = 1; i < args.length; i++) { builder.append(", " + args[i].getClass().getSimpleName()); } throw new NoSuchMethodException(methodName + "(" + builder.toString() + ")"); } else { throw new NoSuchMethodException(methodName + "()"); } } catch (NullPointerException e) { StringBuilder builder = new StringBuilder(String.valueOf(args[0])); for (int i = 1; i < args.length; i++) builder.append("," + String.valueOf(args[i])); throw new NullPointerException("Call " + methodName + "(" + builder.toString() + ")"); } }
From source file:jp.terasoluna.fw.web.struts.form.DynaValidatorActionFormEx.java
/** * CfbNXtv?peBZbg?B//from w w w. j a va 2 s.co m * * <p> * StrutsDynaActionFormv?peB^ * Listz^gpO??A * TCY?AITCY * ?X?A???g?B * </p> * * @param name Zbg?tB?[h * @param index Zbg?CfbNX * @param value Zbg?tB?[hl */ @SuppressWarnings("unchecked") @Override public void set(String name, int index, Object value) { if (log.isDebugEnabled()) { log.debug("set(" + name + ", " + index + ", " + value + ") called."); } Object prop = dynaValues.get(name); if (prop == null) { throw new NullPointerException("No indexed value for '" + name + "[" + index + "]'"); } else if (prop.getClass().isArray()) { if (index < Array.getLength(prop)) { Array.set(prop, index, value); } else { // CfbNX`FbN ActionFormUtil.checkIndexLength(index); // ?VKz?? Object newArray = Array.newInstance(prop.getClass().getComponentType(), index + 1); // zR|?[lgRs?[ System.arraycopy(prop, 0, newArray, 0, Array.getLength(prop)); // R|?[lgZbg Array.set(newArray, index, value); // Q?Rs?[ prop = newArray; } dynaValues.put(name, prop); } else if (prop instanceof List) { if (index < ((List) prop).size()) { ((List) prop).set(index, value); } else { // CfbNX`FbN ActionFormUtil.checkIndexLength(index); Object[] oldValues = ((List) prop).toArray(); Object[] newValues = (Object[]) Array.newInstance(oldValues.getClass().getComponentType(), index + 1); System.arraycopy(oldValues, 0, newValues, 0, oldValues.length); newValues[index] = value; ((List) prop).clear(); ((List) prop).addAll(Arrays.asList(newValues)); } dynaValues.put(name, prop); } else { throw new IllegalArgumentException("Non-indexed property for '" + name + "[" + index + "]'"); } }
From source file:com.laidians.utils.ClassUtils.java
/** * Replacement for <code>Class.forName()</code> that also returns Class instances * for primitives (e.g."int") and array class names (e.g. "String[]"). * Furthermore, it is also capable of resolving inner class names in Java source * style (e.g. "java.lang.Thread.State" instead of "java.lang.Thread$State"). * @param name the name of the Class/* w w w . j a va 2 s .c o m*/ * @param classLoader the class loader to use * (may be <code>null</code>, which indicates the default class loader) * @return Class instance for the supplied name * @throws ClassNotFoundException if the class was not found * @throws LinkageError if the class file could not be loaded * @see Class#forName(String, boolean, ClassLoader) */ public static Class<?> forName(String name, ClassLoader classLoader) throws ClassNotFoundException, LinkageError { Assert.notNull(name, "Name must not be null"); Class<?> clazz = resolvePrimitiveClassName(name); if (clazz == null) { clazz = commonClassCache.get(name); } if (clazz != null) { return clazz; } // "java.lang.String[]" style arrays if (name.endsWith(ARRAY_SUFFIX)) { String elementClassName = name.substring(0, name.length() - ARRAY_SUFFIX.length()); Class<?> elementClass = forName(elementClassName, classLoader); return Array.newInstance(elementClass, 0).getClass(); } // "[Ljava.lang.String;" style arrays if (name.startsWith(NON_PRIMITIVE_ARRAY_PREFIX) && name.endsWith(";")) { String elementName = name.substring(NON_PRIMITIVE_ARRAY_PREFIX.length(), name.length() - 1); Class<?> elementClass = forName(elementName, classLoader); return Array.newInstance(elementClass, 0).getClass(); } // "[[I" or "[[Ljava.lang.String;" style arrays if (name.startsWith(INTERNAL_ARRAY_PREFIX)) { String elementName = name.substring(INTERNAL_ARRAY_PREFIX.length()); Class<?> elementClass = forName(elementName, classLoader); return Array.newInstance(elementClass, 0).getClass(); } ClassLoader classLoaderToUse = classLoader; if (classLoaderToUse == null) { classLoaderToUse = getDefaultClassLoader(); } try { return classLoaderToUse.loadClass(name); } catch (ClassNotFoundException ex) { int lastDotIndex = name.lastIndexOf('.'); if (lastDotIndex != -1) { String innerClassName = name.substring(0, lastDotIndex) + '$' + name.substring(lastDotIndex + 1); try { return classLoaderToUse.loadClass(innerClassName); } catch (ClassNotFoundException ex2) { // swallow - let original exception get through } } throw ex; } }
From source file:com.datos.vfs.util.DelegatingFileSystemOptionsBuilder.java
/** * tries to convert the value and pass it to the given method *//* w w w. j a v a 2 s . c o m*/ private boolean convertValuesAndInvoke(final Method configSetter, final Context ctx) throws FileSystemException { final Class<?>[] parameters = configSetter.getParameterTypes(); if (parameters.length < 2) { return false; } if (!parameters[0].isAssignableFrom(FileSystemOptions.class)) { return false; } final Class<?> valueParameter = parameters[1]; Class<?> type; if (valueParameter.isArray()) { type = valueParameter.getComponentType(); } else { if (ctx.values.length > 1) { return false; } type = valueParameter; } if (type.isPrimitive()) { final Class<?> objectType = PRIMATIVE_TO_OBJECT.get(type.getName()); if (objectType == null) { log.warn(Messages.getString("vfs.provider/config-unexpected-primitive.error", type.getName())); return false; } type = objectType; } final Class<? extends Object> valueClass = ctx.values[0].getClass(); if (type.isAssignableFrom(valueClass)) { // can set value directly invokeSetter(valueParameter, ctx, configSetter, ctx.values); return true; } if (valueClass != String.class) { log.warn(Messages.getString("vfs.provider/config-unexpected-value-class.error", valueClass.getName(), ctx.scheme, ctx.name)); return false; } final Object convertedValues = Array.newInstance(type, ctx.values.length); Constructor<?> valueConstructor; try { valueConstructor = type.getConstructor(STRING_PARAM); } catch (final NoSuchMethodException e) { valueConstructor = null; } if (valueConstructor != null) { // can convert using constructor for (int iterValues = 0; iterValues < ctx.values.length; iterValues++) { try { Array.set(convertedValues, iterValues, valueConstructor.newInstance(new Object[] { ctx.values[iterValues] })); } catch (final InstantiationException e) { throw new FileSystemException(e); } catch (final IllegalAccessException e) { throw new FileSystemException(e); } catch (final InvocationTargetException e) { throw new FileSystemException(e); } } invokeSetter(valueParameter, ctx, configSetter, convertedValues); return true; } Method valueFactory; try { valueFactory = type.getMethod("valueOf", STRING_PARAM); if (!Modifier.isStatic(valueFactory.getModifiers())) { valueFactory = null; } } catch (final NoSuchMethodException e) { valueFactory = null; } if (valueFactory != null) { // can convert using factory method (valueOf) for (int iterValues = 0; iterValues < ctx.values.length; iterValues++) { try { Array.set(convertedValues, iterValues, valueFactory.invoke(null, new Object[] { ctx.values[iterValues] })); } catch (final IllegalAccessException e) { throw new FileSystemException(e); } catch (final InvocationTargetException e) { throw new FileSystemException(e); } } invokeSetter(valueParameter, ctx, configSetter, convertedValues); return true; } return false; }
From source file:org.jsonschema2pojo.integration.json.JsonTypesIT.java
@Test public void arrayItemsAreNotRecursivelyMerged() throws Exception { ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/json/simplePropertiesInArrayItem.json", "com.example", config("sourceType", "json")); Class<?> genType = resultsClassLoader.loadClass("com.example.SimplePropertiesInArrayItem"); // Different array items use different types for the same property; // we don't support union types, so we have to pick one assertEquals(Integer.class, genType.getMethod("getScalar").getReturnType()); thrown.expect(InvalidFormatException.class); thrown.expectMessage("Can not construct instance of java.lang.Integer from String value (\"what\")"); OBJECT_MAPPER.readValue(this.getClass().getResourceAsStream("/json/simplePropertiesInArrayItem.json"), Array.newInstance(genType, 0).getClass()); }
From source file:net.sourceforge.vulcan.web.struts.actions.ManagePluginAction.java
public final ActionForward remove(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { final PluginConfigForm configForm = (PluginConfigForm) form; final String target = configForm.getTarget(); final String[] split = target.split("\\["); final String arrayProperty = split[0]; final int index = Integer.parseInt(split[1].substring(0, split[1].length() - 1)); final BeanWrapper bw = new BeanWrapperImpl(form); final Class<?> type = PropertyUtils.getPropertyType(form, arrayProperty).getComponentType(); Object[] array = (Object[]) bw.getPropertyValue(arrayProperty); Object[] tmp = (Object[]) Array.newInstance(type, array.length - 1); System.arraycopy(array, 0, tmp, 0, index); System.arraycopy(array, index + 1, tmp, index, array.length - index - 1); bw.setPropertyValue(arrayProperty, tmp); configForm.putBreadCrumbsInRequest(request); return mapping.findForward("configure"); }