罗列一下反射机制的一些应用,具体理论以后整理吧。。
1.利用反射机制分析类的能力
import java.util.*;
import java.lang.reflect.*;
public class ReflectionTest {
public static void main(String[] args) {
String name;
Scanner in = new Scanner(System.in);
System.out.println("Entern class name (e.g. java.util.Data):");
name = in.next();
try {
//print class name and superclass name(if != Object)
Class cl = Class.forName(name);
Class supercl = cl.getSuperclass();
String modifiers = Modifier.toString(cl.getModifiers());
if (modifiers.length() > 0)
System.out.print(modifiers + " ");
System.out.print("class " + name);
if (supercl != null && supercl != Object.class)
System.out.print(" extends " + supercl.getName());
System.out.println("\n{\n");
printConstructors(cl);
System.out.println();
printMethods(cl);
System.out.println();
printFields(cl);
System.out.println("}");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* prints all constructors of a class
* @param cl a class
*/
public static void printConstructors(Class cl) {
Constructor[] constructors = cl.getDeclaredConstructors();
for(Constructor c: constructors) {
String name = c.getName();
System.out.print(" ");
String modifiers = Modifier.toString(c.getModifiers());
if (modifiers.length() > 0)
System.out.print(modifiers + " ");
System.out.print(name + "(");
//print parameter types
Class[] paramTypes = c.getParameterTypes();
for (int j = 0; j < paramTypes.length; j++) {
if (j > 0)
System.out.print(", ");
System.out.print(paramTypes[j].getName());
}
System.out.println(");");
}
}
/**
* prints all methods of a class
* @param cl a class
*/
public static void printMethods(Class cl) {
Method[] methods = cl.getDeclaredMethods();
for (Method m: methods) {
Class retType = m.getReturnType();
String name = m.getName();
System.out.print(" ");
//print modifiers,return type and method name
String modifiers = Modifier.toString(m.getModifiers());
if (modifiers.length() > 0)
System.out.print(modifiers + " ");
System.out.print(retType.getName() + " " + name + "(");
//print parameter types
Class[] paramTypes = m.getParameterTypes();
for (int j = 0; j < paramTypes.length; j++) {
if (j > 0)
System.out.println(", ");
System.out.print(paramTypes[j].getName());
}
System.out.println(");");
}
}
/**
* print all fields of a class
* @param cl a class
*/
public static void printFields(Class cl) {
Field[] fields = cl.getDeclaredFields();
for (Field f: fields) {
Class type = f.getType();
String name = f.getName();
System.out.println(" ");
String modifiers = Modifier.toString(f.getModifiers());
if (modifiers.length() > 0)
System.out.print(modifiers + " ");
System.out.println(type.getName() + " " + name + ";");
}
}
}
2.在运行时使用反射分析对象
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
public class ObjectAnalyzer {
private ArrayList<Object> visited = new ArrayList<>();
/**
* Convert an object to String representation that lists all fields
* @param obj an object
* @return a string with the object's class name and all field names and
* values
*/
public String toString(Object obj) {
if (obj == null) return null;
if (visited.contains(obj)) return "...";
visited.add(obj);
Class cl = obj.getClass();
if (cl == String.class) return (String) obj;
if (cl.isArray()) {
String r = cl.getComponentType() + "[]{";
for (int i = 0; i < Array.getLength(obj); i++) {
if (i > 0) r += ",";
Object val = Array.get(obj,i);
if (cl.getComponentType().isPrimitive()) r += val;
else r += toString(val);//递归调用
}
return r + "}";
}
String r = cl.getName();
//inspect the fields of this class and all superclasses
do {
r += "[";
Field[] fields = cl.getDeclaredFields();
AccessibleObject.setAccessible(fields, true);
//get the names and values of all fields
for (Field f: fields) {
if (!Modifier.isStatic(f.getModifiers())) {
if (!r.endsWith("[")) r += ",";
r += f.getName() + "=";
try {
Class t = f.getType();
Object val = f.get(obj);
if (t.isPrimitive()) r += val;
else r += toString(val);
} catch (Exception e) {
e.printStackTrace();
}
}
}
r += "]";
cl = cl.getSuperclass();
} while (cl != null);
return r;
}
}
import java.util.ArrayList;
public class ObjectAnalyzerTest {
public static void main(String[] args) {
ArrayList<Integer> squares = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
squares.add(i * i);
}
System.out.println(new ObjectAnalyzer().toString(squares));
}
}
3.使用反射编写泛型数组代码
import java.lang.reflect.*;
import java.util.*;
/**
* Reflection for manipulating array
* @author corejava
*/
public class GenericArray {
public static void main(String[] args) {
int[] a = {1,2,3};
a = (int[]) goodCopyOf(a,10);
System.out.println(Arrays.toString(a));
String[] b = {"cat","dog","fish"};
b = (String[]) goodCopyOf(b,10);
System.out.println(Arrays.toString(b));
System.out.println("The following call will generate an exception.");
//b = (String[]) badCopyOf(b,10);
}
/**
* This method attempts to grow an array by allocating a new array and copying all elements.
* @param a the array to grow
* @param newLength the new length
* @return a larger array that contains all elements of a. However, the returned array has
* type Object[], not the same type as a.
*/
public static Object[] badCopyOf(Object[] a, int newLength) {
Object[] newArray = new Object[newLength];
System.arraycopy(a, 0, newArray, 0, Math.min(a.length, newLength));
return newArray;
}
/**
* This method grows an array by allocating a new array of the same type and copying all elements.
* @param a the array to grow. This can be an object array or a primitive type array.
* @param newLength the new length
* @return a larger array that contains all elements of a.
*/
public static Object goodCopyOf(Object a, int newLength) {
Class cl = a.getClass();
if (!cl.isArray()) return null;
Class componentType = cl.getComponentType();
int length = Array.getLength(a);
Object newArray = Array.newInstance(componentType, newLength);
System.arraycopy(a, 0, newArray, 0, Math.min(length, newLength));
return newArray;
}
}