类java.lang.reflect.Array源码实例Demo

下面列出了怎么用java.lang.reflect.Array的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: jdk8u-dev-jdk   文件: MLetObjectInputStream.java
/**
 * 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);
    }
}
 
源代码2 项目: PE-HFT-Java   文件: CryptograhicUtils.java
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;
}
 
源代码3 项目: HtmlNative   文件: CoerceLuaToJava.java
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;
	}
	
}
 
源代码4 项目: xlsbeans   文件: IterateTablesProcessor.java
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.");
  }
}
 
源代码5 项目: jpmml-xgboost   文件: XGBoostDataInput.java
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;
}
 
源代码6 项目: p4ic4idea   文件: SymbolicLinkHelper.java
/**
 * 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;
}
 
源代码7 项目: commons-jexl   文件: JexlArithmetic.java
/**
 * 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;
}
 
源代码8 项目: linstor-server   文件: FlagsHelper.java
@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()));
}
 
源代码9 项目: 10000sentences   文件: DBG.java
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);
}
 
源代码10 项目: dolphin   文件: AnnotationAttributes.java
@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;
}
 
源代码11 项目: EasyTransaction   文件: ReflectUtil.java
/**
 * 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;
	}
}
 
源代码12 项目: AndroidDemo   文件: DiskLruCache.java
@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;
}
 
源代码13 项目: jdk8u_jdk   文件: XMBeanNotifications.java
@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();
}
 
源代码14 项目: geopackage-core-java   文件: UserCoreDao.java
/**
 * 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;
}
 
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();
}
 
源代码16 项目: letv   文件: b.java
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;
}
 
源代码17 项目: football-events   文件: StreamsTester.java
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);
    }
}
 
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();
}
 
源代码19 项目: jdk8u-jdk   文件: EventListenerAggregate.java
/**
 * 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;
}
 
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();
}
 
源代码21 项目: openjdk-jdk9   文件: ObjectInputStream.java
/**
 * 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;
}
 
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);
    }
}
 
源代码23 项目: xlsbeans   文件: IterateTablesProcessor.java
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.");
  }
}
 
源代码24 项目: Android-Router   文件: ValueParser.java
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;
}
 
源代码25 项目: jdk8u-jdk   文件: EventListenerAggregate.java
/**
 * 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;
}
 
@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);
    }
}
 
源代码27 项目: openjdk-jdk9   文件: TestArray.java
private static <T> T[] getArray(Class<T> component, int length, Object object) {
    Class type = object.getClass();
    if (!type.isArray()) {
        throw new Error("array expected");
    }
    if (!type.getComponentType().equals(component)) {
        throw new Error("unexpected component type");
    }
    if (length != Array.getLength(object)) {
        throw new Error("unexpected array length");
    }
    return (T[]) object;
}
 
源代码28 项目: Framez   文件: JavaTools.java
public <T> T[] concatenate (T[] a, T[] b) {
    int aLen = a.length;
    int bLen = b.length;

    @SuppressWarnings("unchecked")
	T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen + bLen);
    System.arraycopy(a, 0, c, 0, aLen);
    System.arraycopy(b, 0, c, aLen, bLen);

    return c;
}
 
源代码29 项目: lams   文件: ResolvableType.java
private Class<?> resolveClass() {
	if (this.type instanceof Class || this.type == null) {
		return (Class<?>) this.type;
	}
	if (this.type instanceof GenericArrayType) {
		Class<?> resolvedComponent = getComponentType().resolve();
		return (resolvedComponent != null ? Array.newInstance(resolvedComponent, 0).getClass() : null);
	}
	return resolveType().resolve();
}
 
源代码30 项目: MiBandDecompiled   文件: ByteMatrix.java
public ByteMatrix(int i, int j)
{
    int ai[] = {
        j, i
    };
    a = (byte[][])Array.newInstance(Byte.TYPE, ai);
    b = i;
    c = j;
}