Java/Reflection/Array Reflection
Содержание
- 1 Array Reflection: create instance
- 2 Array Reflection: getComponentType()
- 3 Array Reflection: get length
- 4 Array Reflection: Multi Array Reflection
- 5 Array Reflection: name and type
- 6 Check if the given object is an array (primitve or native).
- 7 Creating an Array: A 10x20 2-dimensional int array.
- 8 Creating an Array: An array of 10 int-arrays.
- 9 Creating an Array: An array of 10 ints.
- 10 Determining If an Object Is an Array
- 11 Getting and Setting the Value of an Element in an Array Object
- 12 Getting the Component Type of an Array Object
- 13 Getting the Length and Dimensions of an Array Object
- 14 return an Object array for the given object.
- 15 Using reflection to check array type and length
- 16 Using reflection to create, fill, and display an array
Array Reflection: create instance
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
* Copyright (c) 1995-1998 Sun Microsystems, Inc. All Rights Reserved.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for NON-COMMERCIAL purposes and without fee is hereby granted
* provided that this copyright notice appears in all copies. Please refer to
* the file "copyright.html" for further important copyright and licensing
* information.
*
* SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
* SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
* NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
* LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES.
*/
import java.lang.reflect.Array;
public class SampleCreateArrayReflection {
public static void main(String[] args) {
int[] originalArray = { 55, 66 };
int[] biggerArray = (int[]) doubleArray(originalArray);
System.out.println("originalArray:");
for (int k = 0; k < Array.getLength(originalArray); k++)
System.out.println(originalArray[k]);
System.out.println("biggerArray:");
for (int k = 0; k < Array.getLength(biggerArray); k++)
System.out.println(biggerArray[k]);
}
static Object doubleArray(Object source) {
int sourceLength = Array.getLength(source);
Class arrayClass = source.getClass();
Class componentClass = arrayClass.getComponentType();
Object result = Array.newInstance(componentClass, sourceLength * 2);
System.arraycopy(source, 0, result, 0, sourceLength);
return result;
}
}
Array Reflection: getComponentType()
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
* Copyright (c) 1995-1998 Sun Microsystems, Inc. All Rights Reserved.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for NON-COMMERCIAL purposes and without fee is hereby granted
* provided that this copyright notice appears in all copies. Please refer to
* the file "copyright.html" for further important copyright and licensing
* information.
*
* SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
* SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
* NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
* LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES.
*/
import java.awt.Button;
public class SampleComponentReflection {
public static void main(String[] args) {
int[] ints = new int[2];
Button[] buttons = new Button[6];
String[][] twoDim = new String[4][5];
printComponentType(ints);
printComponentType(buttons);
printComponentType(twoDim);
}
static void printComponentType(Object array) {
Class arrayClass = array.getClass();
String arrayName = arrayClass.getName();
Class componentClass = arrayClass.getComponentType();
String componentName = componentClass.getName();
System.out.println("Array: " + arrayName + ", Component: "
+ componentName);
}
}
Array Reflection: get length
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
* Copyright (c) 1995-1998 Sun Microsystems, Inc. All Rights Reserved.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for NON-COMMERCIAL purposes and without fee is hereby granted
* provided that this copyright notice appears in all copies. Please refer to
* the file "copyright.html" for further important copyright and licensing
* information.
*
* SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
* SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
* NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
* LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES.
*/
import java.lang.reflect.Array;
public class SampleGetArrayReflection {
public static void main(String[] args) {
int[] sourceInts = { 12, 78 };
int[] destInts = new int[2];
copyArray(sourceInts, destInts);
String[] sourceStrgs = { "Hello ", "there ", "everybody" };
String[] destStrgs = new String[3];
copyArray(sourceStrgs, destStrgs);
}
public static void copyArray(Object source, Object dest) {
for (int i = 0; i < Array.getLength(source); i++) {
Array.set(dest, i, Array.get(source, i));
System.out.println(Array.get(dest, i));
}
}
}
Array Reflection: Multi Array Reflection
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
* Copyright (c) 1995-1998 Sun Microsystems, Inc. All Rights Reserved.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for NON-COMMERCIAL purposes and without fee is hereby granted
* provided that this copyright notice appears in all copies. Please refer to
* the file "copyright.html" for further important copyright and licensing
* information.
*
* SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
* SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
* NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
* LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES.
*/
import java.lang.reflect.Array;
public class SampleMultiArrayReflection {
public static void main(String[] args) {
// The oneDimA and oneDimB objects are one dimensional int arrays
// with 5 elements.
int[] dim1 = { 5 };
int[] oneDimA = (int[]) Array.newInstance(int.class, dim1);
int[] oneDimB = (int[]) Array.newInstance(int.class, 5);
// The twoDimStr object is a 5 X 10 array of String objects.
int[] dimStr = { 5, 10 };
String[][] twoDimStr = (String[][]) Array.newInstance(String.class,
dimStr);
// The twoDimA object is an array of 12 int arrays. The tail
// dimension is not defined. It is equivalent to the array
// created as follows:
// int[][] ints = new int[12][];
int[] dimA = { 12 };
int[][] twoDimA = (int[][]) Array.newInstance(int[].class, dimA);
}
}
Array Reflection: name and type
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
* Copyright (c) 1995-1998 Sun Microsystems, Inc. All Rights Reserved.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for NON-COMMERCIAL purposes and without fee is hereby granted
* provided that this copyright notice appears in all copies. Please refer to
* the file "copyright.html" for further important copyright and licensing
* information.
*
* SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
* SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
* NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
* LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES.
*/
import java.awt.Button;
import java.awt.TextField;
import java.lang.reflect.Field;
public class SampleArrayReflection {
public static void main(String[] args) {
KeyPad target = new KeyPad();
printArrayNames(target);
}
static void printArrayNames(Object target) {
Class targetClass = target.getClass();
Field[] publicFields = targetClass.getFields();
for (int i = 0; i < publicFields.length; i++) {
String fieldName = publicFields[i].getName();
Class typeClass = publicFields[i].getType();
String fieldType = typeClass.getName();
if (typeClass.isArray()) {
System.out.println("Name: " + fieldName + ", Type: "
+ fieldType);
}
}
}
}
class KeyPad {
public boolean alive;
public Button power;
public Button[] letters;
public int[] codes;
public TextField[] rows;
public boolean[] states;
}
Check if the given object is an array (primitve or native).
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
public class Main {
/**
* Check if the given object is an array (primitve or native).
*
* @param obj Object to test.
* @return True of the object is an array.
*/
public static boolean isArray(final Object obj) {
if (obj != null)
return obj.getClass().isArray();
return false;
}
}
Creating an Array: A 10x20 2-dimensional int array.
import java.lang.reflect.Array;
public class Main {
public static void main(String[] argv) throws Exception {
int[][] ints2 = (int[][]) Array.newInstance(int.class, new int[] { 10, 20 });
}
}
Creating an Array: An array of 10 int-arrays.
import java.lang.reflect.Array;
public class Main {
public static void main(String[] argv) throws Exception {
int[][] ints2 = (int[][]) Array.newInstance(int[].class, 10);
}
}
Creating an Array: An array of 10 ints.
import java.lang.reflect.Array;
public class Main {
public static void main(String[] argv) throws Exception {
int[] ints = (int[]) Array.newInstance(int.class, 10);
}
}
Determining If an Object Is an Array
public class Main {
public static void main(String[] argv) throws Exception {
boolean b = "".getClass().isArray();
if (b) {
System.out.println("object is an array");
}
}
}
Getting and Setting the Value of an Element in an Array Object
import java.lang.reflect.Array;
public class Main {
public static void main(String[] argv) throws Exception {
int[] array = { 1, 2, 3 };
// Get the value of the third element.
Object o = Array.get(array, 2);
// Set the value of the third element.
Array.set(array, 2, 1);
}
}
Getting the Component Type of an Array Object
public class Main {
public static void main(String[] argv) throws Exception {
Object o = new int[1][2][3];
o.getClass().getComponentType();
}
}
Getting the Length and Dimensions of an Array Object
import java.lang.reflect.Array;
public class Main {
public static void main(String[] argv) throws Exception {
Object o = new int[1][2][3];
int len = Array.getLength(o); // 1
System.out.println(len);
int dim = getDim(o); // 3
System.out.println(dim);
}
public static int getDim(Object array) {
int dim = 0;
Class cls = array.getClass();
while (cls.isArray()) {
dim++;
cls = cls.getComponentType();
}
return dim;
}
}
return an Object array for the given object.
import java.lang.reflect.Array;
/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
public class Main {
/**
* @return an Object array for the given object.
*
* @param obj Object to convert to an array. Converts primitive
* arrays to Object arrays consisting of their wrapper
* classes. If the object is not an array (object or primitve)
* then a new array of the given type is created and the
* object is set as the sole element.
*/
public static Object[] toArray(final Object obj) {
// if the object is an array, the cast and return it.
if (obj instanceof Object[]) {
return (Object[])obj;
}
// if the object is an array of primitives then wrap the array
Class type = obj.getClass();
Object array;
if (type.isArray()) {
int length = Array.getLength(obj);
Class componentType = type.getComponentType();
array = Array.newInstance(componentType, length);
for (int i=0; i<length; i++) {
Array.set(array, i, Array.get(obj, i));
}
}
else {
array = Array.newInstance(type, 1);
Array.set(array, 0, obj);
}
return (Object[])array;
}
}
Using reflection to check array type and length
import java.lang.reflect.Array;
public class MainClass {
public static void main(String args[]) {
String data[] = new String[3];
data[0] = "Java";
printType(data);
}
private static void printType(Object object) {
Class type = object.getClass();
if (type.isArray()) {
Class dataType = type.getComponentType();
System.out.println("Array of: " + dataType);
System.out.println(" Length: " + Array.getLength(object));
}
}
}
Using reflection to create, fill, and display an array
import java.lang.reflect.Array;
import java.util.Random;
public class MainClass {
public static void main(String args[]) {
Object array = Array.newInstance(int.class, 3);
printType(array);
fillArray(array);
displayArray(array);
}
private static void printType(Object object) {
Class type = object.getClass();
if (type.isArray()) {
Class elementType = type.getComponentType();
System.out.println("Array of: " + elementType);
System.out.println("Array size: " + Array.getLength(object));
}
}
private static void fillArray(Object array) {
int length = Array.getLength(array);
Random generator = new Random(System.currentTimeMillis());
for (int i = 0; i < length; i++) {
int random = generator.nextInt();
Array.setInt(array, i, random);
}
}
private static void displayArray(Object array) {
int length = Array.getLength(array);
for (int i = 0; i < length; i++) {
int value = Array.getInt(array, i);
System.out.println("Position: " + i + ", value: " + value);
}
}
}