下面列出了怎么用java.lang.reflect.Array的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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);
}
}
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;
}
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;
}
}
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.");
}
}
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;
}
/**
* 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;
}
/**
* 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;
}
@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()));
}
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);
}
@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;
}
/**
* 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;
}
}
@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;
}
@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();
}
/**
* 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();
}
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;
}
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();
}
/**
* 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();
}
/**
* 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);
}
}
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.");
}
}
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;
}
/**
* 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);
}
}
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;
}
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;
}
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();
}
public ByteMatrix(int i, int j)
{
int ai[] = {
j, i
};
a = (byte[][])Array.newInstance(Byte.TYPE, ai);
b = i;
c = j;
}