java.lang.reflect.Array Java Examples
The following examples show how to use
java.lang.reflect.Array.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ParamFlowChecker.java From Sentinel-Dashboard-Nacos with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") private static Collection<Object> toCollection(Object value) { if (value instanceof Collection) { return (Collection<Object>)value; } else if (value.getClass().isArray()) { List<Object> params = new ArrayList<Object>(); int length = Array.getLength(value); for (int i = 0; i < length; i++) { Object param = Array.get(value, i); params.add(param); } return params; } else { return Collections.singletonList(value); } }
Example #2
Source File: XGBoostDataInput.java From jpmml-xgboost with GNU Affero General Public License v3.0 | 6 votes |
public <E extends Loadable> E[] readObjectArray(Class<? extends E> clazz, int length) throws IOException { E[] result = (E[])Array.newInstance(clazz, length); for(int i = 0; i < result.length; i++){ E object; try { object = clazz.newInstance(); } catch(ReflectiveOperationException roe){ throw new IOException(roe); } object.load(this); result[i] = object; } return result; }
Example #3
Source File: SymbolicLinkHelper.java From p4ic4idea with Apache License 2.0 | 6 votes |
/** * Creates a symbolic link to a target. * * @param source * the path of the path to the file to move * @param target * the path to the target file * @return the path to the target file */ public static String move(String source, String target) { if (symbolicLinkCapable && source != null && target != null) { try { Object sourcePath = getPathMethod.invoke(fileSystem, new Object[] { source, new String[] {} }); Object targetPath = getPathMethod.invoke(fileSystem, new Object[] { target, new String[] {} }); if (sourcePath != null && targetPath != null) { Object pathObject = move.invoke(null, sourcePath, targetPath, Array.newInstance(copyOptionClass, 0)); if (pathObject != null) { return pathObject.toString(); } } } catch (Throwable thr) { Log.error("Unexpected exception invoking method: " + thr.getLocalizedMessage()); Log.exception(thr); } } return null; }
Example #4
Source File: CoerceLuaToJava.java From HtmlNative with Apache License 2.0 | 6 votes |
public Object coerce(LuaValue value) { switch ( value.type() ) { case LuaValue.TTABLE: { int n = value.length(); Object a = Array.newInstance(componentType, n); for ( int i=0; i<n; i++ ) Array.set(a, i, componentCoercion.coerce(value.get(i+1))); return a; } case LuaValue.TUSERDATA: return value.touserdata(); case LuaValue.TNIL: return null; default: return null; } }
Example #5
Source File: DBG.java From 10000sentences with Apache License 2.0 | 6 votes |
private static String objectToString(Object object) { if (object == null) { return "null"; } else if (object.getClass().isArray()) { StringBuilder result = new StringBuilder(); result.append("["); for (int i = 0; i < Array.getLength(object); i++) { result.append(objectToString(Array.get(object, i))); result.append(", "); } result.append("]"); return result.toString(); } else if (object instanceof Throwable) { Throwable throwable = (Throwable) object; ByteArrayOutputStream out = new ByteArrayOutputStream(); throwable.printStackTrace(new PrintStream(out)); try { out.close(); } catch (Exception ignore) { } return new String(out.toByteArray()); } return String.valueOf(object); }
Example #6
Source File: JexlArithmetic.java From commons-jexl with Apache License 2.0 | 6 votes |
/** * Check for emptiness of various types: Number, Collection, Array, Map, String. * * @param object the object to check the emptiness of * @param def the default value if object emptyness can not be determined * @return the boolean or null if there is no arithmetic solution */ public Boolean isEmpty(Object object, Boolean def) { if (object instanceof Number) { double d = ((Number) object).doubleValue(); return Double.isNaN(d) || d == 0.d ? Boolean.TRUE : Boolean.FALSE; } if (object instanceof CharSequence) { return ((CharSequence) object).length() == 0 ? Boolean.TRUE : Boolean.FALSE; } if (object.getClass().isArray()) { return Array.getLength(object) == 0 ? Boolean.TRUE : Boolean.FALSE; } if (object instanceof Collection<?>) { return ((Collection<?>) object).isEmpty() ? Boolean.TRUE : Boolean.FALSE; } // Map isn't a collection if (object instanceof Map<?, ?>) { return ((Map<?, ?>) object).isEmpty() ? Boolean.TRUE : Boolean.FALSE; } return def; }
Example #7
Source File: CryptograhicUtils.java From PE-HFT-Java with GNU General Public License v3.0 | 6 votes |
public static String decrypt (String message, String key) throws InvalidKeyException, UnsupportedEncodingException { byte[] encryptedText; byte[] decryptedText; Rijndael cipher = new Rijndael(); //create the key byte[] keyBytes = key.getBytes(); Object keyObject = cipher.makeKey(keyBytes, 16); //make the length of the string a multiple of //the block size if ((message.length() % 16) != 0) { while ((message.length() % 16) != 0) { message += " "; } } //initialize byte arrays that will hold encrypted/decrypted //text encryptedText = Base64.decode(message); decryptedText = new byte[message.length()]; //Iterate over the byte arrays by 16-byte blocks and decrypt. for (int i=0; i<Array.getLength(encryptedText); i+=16) { cipher.decrypt(encryptedText, i, decryptedText, i, keyObject, 16); } String decryptedString = new String(decryptedText, "UTF8"); return decryptedString; }
Example #8
Source File: FlagsHelper.java From linstor-server with GNU General Public License v3.0 | 6 votes |
@SuppressWarnings("unchecked") public static <E extends Enum<E> & Flags> E[] toFlagsArray( Class<E> enumClass, StateFlags<E> flags, AccessContext accCtx ) throws AccessDeniedException { EnumSet<E> values = EnumSet.allOf(enumClass); List<E> setFlags = new ArrayList<>(); for (E val : values) { if (flags.isSet(accCtx, val)) { setFlags.add(val); } } return setFlags.toArray((E[]) Array.newInstance(enumClass, setFlags.size())); }
Example #9
Source File: IterateTablesProcessor.java From xlsbeans with Apache License 2.0 | 6 votes |
public void doProcess(WSheet wSheet, Object obj, Field field, Annotation ann, AnnotationReader reader, XLSBeansConfig config, List<NeedPostProcess> needPostProcess) throws Exception { IterateTables iterateTables = (IterateTables) ann; Class<?> fieldType = field.getType(); // create multi-table objects. List<?> value = createTables(wSheet, iterateTables, reader, config, needPostProcess); if (List.class.isAssignableFrom(fieldType)) { field.set(obj, value); } else if (fieldType.isArray()) { Class<?> type = fieldType.getComponentType(); Object array = Array.newInstance(type, value.size()); for (int i = 0; i < value.size(); i++) { Array.set(array, i, value.get(i)); } field.set(obj, array); } else { throw new XLSBeansException("Arguments of '" + field.toString() + "' is invalid."); } }
Example #10
Source File: AnnotationAttributes.java From dolphin with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") private <T> T doGet(String attributeName, Class<T> expectedType) { Assert.hasText(attributeName, "attributeName must not be null or empty"); Object value = get(attributeName); Assert.notNull(value, String.format("Attribute '%s' not found", attributeName)); if (!expectedType.isInstance(value)) { if (expectedType.isArray() && expectedType.getComponentType().isInstance(value)) { Object arrayValue = Array.newInstance(expectedType.getComponentType(), 1); Array.set(arrayValue, 0, value); value = arrayValue; } else { throw new IllegalArgumentException( String.format("Attribute '%s' is of type [%s], but [%s] was expected. Cause: ", attributeName, value.getClass().getSimpleName(), expectedType.getSimpleName())); } } return (T) value; }
Example #11
Source File: ReflectUtil.java From EasyTransaction with Apache License 2.0 | 6 votes |
/** * Get the underlying class for a type, or null if the type is a variable * type. * * @param type * the type * @return the underlying class */ private static Class<?> getClass(Type type) { if (type instanceof Class) { return (Class<?>) type; } else if (type instanceof ParameterizedType) { return getClass(((ParameterizedType) type).getRawType()); } else if (type instanceof GenericArrayType) { Type componentType = ((GenericArrayType) type) .getGenericComponentType(); Class<?> componentClass = getClass(componentType); if (componentClass != null) { return Array.newInstance(componentClass, 0).getClass(); } else { return null; } } else { return null; } }
Example #12
Source File: DiskLruCache.java From AndroidDemo with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") private static <T> T[] copyOfRange(T[] original, int start, int end) { final int originalLength = original.length; // For exception priority compatibility. if (start > end) { throw new IllegalArgumentException(); } if (start < 0 || start > originalLength) { throw new ArrayIndexOutOfBoundsException(); } final int resultLength = end - start; final int copyLength = Math.min(resultLength, originalLength - start); final T[] result = (T[]) Array .newInstance(original.getClass().getComponentType(), resultLength); System.arraycopy(original, start, result, 0, copyLength); return result; }
Example #13
Source File: XMBeanNotifications.java From jdk8u_jdk with GNU General Public License v2.0 | 6 votes |
@Override public String toString() { if (userData == null) { return null; } if (userData.getClass().isArray()) { String name = Utils.getArrayClassName(userData.getClass().getName()); int length = Array.getLength(userData); return name + "[" + length + "]"; } if (userData instanceof CompositeData || userData instanceof TabularData) { return userData.getClass().getName(); } return userData.toString(); }
Example #14
Source File: MethodReferenceTestVarArgsSuper.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
String xvO(Object... vi) { StringBuilder sb = new StringBuilder("xvO:"); for (Object i : vi) { if (i.getClass().isArray()) { sb.append("["); int len = Array.getLength(i); for (int x = 0; x < len; ++x) { sb.append(Array.get(i, x)); sb.append(","); } sb.append("]"); } else { sb.append(i); } sb.append("*"); } return sb.toString(); }
Example #15
Source File: MLetObjectInputStream.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 6 votes |
/** * Use the given ClassLoader rather than using the system class */ @Override protected Class<?> resolveClass(ObjectStreamClass objectstreamclass) throws IOException, ClassNotFoundException { String s = objectstreamclass.getName(); if (s.startsWith("[")) { int i; for (i = 1; s.charAt(i) == '['; i++); Class<?> class1; if (s.charAt(i) == 'L') { class1 = loader.loadClass(s.substring(i + 1, s.length() - 1)); } else { if (s.length() != i + 1) throw new ClassNotFoundException(s); class1 = primitiveType(s.charAt(i)); } int ai[] = new int[i]; for (int j = 0; j < i; j++) ai[j] = 0; return Array.newInstance(class1, ai).getClass(); } else { return loader.loadClass(s); } }
Example #16
Source File: EventListenerAggregate.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
/** * Removes a listener that is equal to the given one from this aggregate. * <code>equals()</code> method is used to compare listeners. * * @param listener the listener to be removed * * @return <code>true</code> if this aggregate contained the specified * <code>listener</code>; <code>false</code> otherwise * * @throws ClassCastException if <code>listener</code> is not * an instatce of <code>listenerClass</code> specified * in the constructor */ public synchronized boolean remove(EventListener listener) { Class<?> listenerClass = getListenerClass(); if (!listenerClass.isInstance(listener)) { // null is not an instance of any class throw new ClassCastException("listener " + listener + " is not " + "an instance of listener class " + listenerClass); } for (int i = 0; i < listenerList.length; i++) { if (listenerList[i].equals(listener)) { EventListener[] tmp = (EventListener[])Array.newInstance(listenerClass, listenerList.length - 1); System.arraycopy(listenerList, 0, tmp, 0, i); System.arraycopy(listenerList, i + 1, tmp, i, listenerList.length - i - 1); listenerList = tmp; return true; } } return false; }
Example #17
Source File: ValueParser.java From Android-Router with Apache License 2.0 | 6 votes |
private static Object newArray(String arrayType, int length) throws ClassNotFoundException { Object arr; if ("int".equals(arrayType)) { arr = new int[length]; } else if ("boolean".equals(arrayType)) { arr = new boolean[length]; } else if ("long".equals(arrayType)) { arr = new long[length]; } else if ("double".equals(arrayType)) { arr = new double[length]; } else if ("float".equals(arrayType)) { arr = new float[length]; } else if ("java.lang.String".equals(arrayType)) { arr = new String[length]; } else { arr = Array.newInstance(Class.forName(arrayType), length); } return arr; }
Example #18
Source File: IterateTablesProcessor.java From xlsbeans with Apache License 2.0 | 6 votes |
public void doProcess(WSheet wSheet, Object obj, Field field, Annotation ann, AnnotationReader reader, XLSBeansConfig config, List<NeedPostProcess> needPostProcess) throws Exception { IterateTables iterateTables = (IterateTables) ann; Class<?> fieldType = field.getType(); // create multi-table objects. List<?> value = createTables(wSheet, iterateTables, reader, config, needPostProcess); if (List.class.isAssignableFrom(fieldType)) { field.set(obj, value); } else if (fieldType.isArray()) { Class<?> type = fieldType.getComponentType(); Object array = Array.newInstance(type, value.size()); for (int i = 0; i < value.size(); i++) { Array.set(array, i, value.get(i)); } field.set(obj, array); } else { throw new XLSBeansException("Arguments of '" + field.toString() + "' is invalid."); } }
Example #19
Source File: ArrayCopyIntrinsificationTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
private void testHelper(String name, Object src) { int srcLength = Array.getLength(src); // Complete array copy test(name, src, 0, newArray(src, srcLength), 0, srcLength); for (int length : new int[]{0, 1, srcLength - 1, srcLength}) { // Partial array copying test(name, src, 0, newArray(src, length), 0, length); test(name, src, srcLength - length, newArray(src, length), 0, length); test(name, src, 0, newArray(src, srcLength), 0, length); } if (srcLength > 1) { test(name, src, 0, src, 1, srcLength - 1); } }
Example #20
Source File: ObjectInputStream.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * If resolveObject has been enabled and given object does not have an * exception associated with it, calls resolveObject to determine * replacement for object, and updates handle table accordingly. Returns * replacement object, or echoes provided object if no replacement * occurred. Expects that passHandle is set to given object's handle prior * to calling this method. */ private Object checkResolve(Object obj) throws IOException { if (!enableResolve || handles.lookupException(passHandle) != null) { return obj; } Object rep = resolveObject(obj); if (rep != obj) { // The type of the original object has been filtered but resolveObject // may have replaced it; filter the replacement's type if (rep != null) { if (rep.getClass().isArray()) { filterCheck(rep.getClass(), Array.getLength(rep)); } else { filterCheck(rep.getClass(), -1); } } handles.setObject(passHandle, rep); } return rep; }
Example #21
Source File: MethodReferenceTestVarArgsSuperDefault.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
default String xvO(Object... vi) { StringBuilder sb = new StringBuilder("xvO:"); for (Object i : vi) { if (i.getClass().isArray()) { sb.append("["); int len = Array.getLength(i); for (int x = 0; x < len; ++x) { sb.append(Array.get(i, x)); sb.append(","); } sb.append("]"); } else { sb.append(i); } sb.append("*"); } return sb.toString(); }
Example #22
Source File: EventListenerAggregate.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
/** * Removes a listener that is equal to the given one from this aggregate. * <code>equals()</code> method is used to compare listeners. * * @param listener the listener to be removed * * @return <code>true</code> if this aggregate contained the specified * <code>listener</code>; <code>false</code> otherwise * * @throws ClassCastException if <code>listener</code> is not * an instatce of <code>listenerClass</code> specified * in the constructor */ public synchronized boolean remove(EventListener listener) { Class<?> listenerClass = getListenerClass(); if (!listenerClass.isInstance(listener)) { // null is not an instance of any class throw new ClassCastException("listener " + listener + " is not " + "an instance of listener class " + listenerClass); } for (int i = 0; i < listenerList.length; i++) { if (listenerList[i].equals(listener)) { EventListener[] tmp = (EventListener[])Array.newInstance(listenerClass, listenerList.length - 1); System.arraycopy(listenerList, 0, tmp, 0, i); System.arraycopy(listenerList, i + 1, tmp, i, listenerList.length - i - 1); listenerList = tmp; return true; } } return false; }
Example #23
Source File: MethodReferenceTestVarArgsThis.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
String xvO(Object... vi) { StringBuilder sb = new StringBuilder("xvO:"); for (Object i : vi) { if (i.getClass().isArray()) { sb.append("["); int len = Array.getLength(i); for (int x = 0; x < len; ++x) { sb.append(Array.get(i, x)); sb.append(","); } sb.append("]"); } else { sb.append(i); } sb.append("*"); } return sb.toString(); }
Example #24
Source File: StreamsTester.java From football-events with MIT License | 6 votes |
private <T> T[] load(URL resource, Class<T> type) { Objects.requireNonNull(resource, "Null resource"); ObjectMapper mapper = new ObjectMapper(); // noinspection deprecation mapper.registerModule(new JSR310Module()); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); var arrayType = (Class<T[]>) Array.newInstance(type, 0).getClass(); try { return mapper.readValue(resource.toURI().toURL(), arrayType); } catch (IOException | URISyntaxException e) { throw new RuntimeException(e); } }
Example #25
Source File: b.java From letv with Apache License 2.0 | 6 votes |
public static Class<?> b(Type type) { Object obj = type; while (!(obj instanceof Class)) { if (obj instanceof ParameterizedType) { Type rawType = ((ParameterizedType) obj).getRawType(); a.a(rawType instanceof Class); return (Class) rawType; } else if (obj instanceof GenericArrayType) { return Array.newInstance(b(((GenericArrayType) obj).getGenericComponentType()), 0).getClass(); } else { if (obj instanceof TypeVariable) { return Object.class; } if (obj instanceof WildcardType) { obj = ((WildcardType) obj).getUpperBounds()[0]; } else { throw new IllegalArgumentException(new StringBuilder(z[0]).append(obj).append(z[2]).append(obj == null ? z[1] : obj.getClass().getName()).toString()); } } } return (Class) obj; }
Example #26
Source File: UserCoreDao.java From geopackage-core-java with MIT License | 6 votes |
/** * Build where args for ids in the nested SQL query * * @param nestedArgs * nested SQL args * @param whereArgs * where arguments * @return where args * @since 3.4.0 */ public String[] buildWhereInArgs(String[] nestedArgs, String[] whereArgs) { String[] args = whereArgs; if (args == null) { args = nestedArgs; } else if (nestedArgs != null) { args = (String[]) Array.newInstance(String.class, whereArgs.length + nestedArgs.length); System.arraycopy(whereArgs, 0, args, 0, whereArgs.length); System.arraycopy(nestedArgs, 0, args, whereArgs.length, nestedArgs.length); } return args; }
Example #27
Source File: AutoBuffer.java From h2o-2 with Apache License 2.0 | 5 votes |
public <T extends Iced> T[][] getAA(Class<T> tc) { _arys++; long xy = getZA(); if( xy == -1 ) return null; int x=(int)(xy>>32); // Leading nulls int y=(int)xy; // Middle non-zeros int z = y==0 ? 0 : getInt(); // Trailing nulls Class<T[]> tcA = (Class<T[]>) Array.newInstance(tc, 0).getClass(); T[][] ts = (T[][]) Array.newInstance(tcA, x+y+z); for( int i = x; i < x+y; ++i ) ts[i] = getA(tc); return ts; }
Example #28
Source File: ArrayConverter.java From httpdoc with Apache License 2.0 | 5 votes |
@Override public Map<String, String[]> convert(String name, Object value, ConversionProvider provider) throws Exception { Map<String, String[]> map = new LinkedHashMap<String, String[]>(); int length = Array.getLength(value); for (int i = 0; i < length; i++) { Object item = Array.get(value, i); Map<String, String[]> m = provider.convert(name + "[" + i + "]", item); map.putAll(m); } return map; }
Example #29
Source File: BeanWrapperImpl.java From blog_demos with Apache License 2.0 | 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 #30
Source File: AopProxyUtils.java From spring-analysis-note with MIT License | 5 votes |
/** * Adapt the given arguments to the target signature in the given method, * if necessary: in particular, if a given vararg argument array does not * match the array type of the declared vararg parameter in the method. * @param method the target method * @param arguments the given arguments * @return a cloned argument array, or the original if no adaptation is needed * @since 4.2.3 */ static Object[] adaptArgumentsIfNecessary(Method method, @Nullable Object[] arguments) { if (ObjectUtils.isEmpty(arguments)) { return new Object[0]; } if (method.isVarArgs()) { Class<?>[] paramTypes = method.getParameterTypes(); if (paramTypes.length == arguments.length) { int varargIndex = paramTypes.length - 1; Class<?> varargType = paramTypes[varargIndex]; if (varargType.isArray()) { Object varargArray = arguments[varargIndex]; if (varargArray instanceof Object[] && !varargType.isInstance(varargArray)) { Object[] newArguments = new Object[arguments.length]; System.arraycopy(arguments, 0, newArguments, 0, varargIndex); Class<?> targetElementType = varargType.getComponentType(); int varargLength = Array.getLength(varargArray); Object newVarargArray = Array.newInstance(targetElementType, varargLength); System.arraycopy(varargArray, 0, newVarargArray, 0, varargLength); newArguments[varargIndex] = newVarargArray; return newArguments; } } } } return arguments; }