Reflection 的简单应用,包括field, method,constructor的应用。
package com.gaoqian.reflection;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
abstract class BaseClass1 {
private int bi;
protected String bs;
public char bc;
public BaseClass1(int bin, String bstr, char bch) {
this.bi = bin;
this.bs = bstr;
this.bc = bch;
}
public int getIntValue() {
return bi;
}
public void setIntValue(int in) {
this.bi = in;
}
public abstract String out();
}
class DerivedClass2 extends BaseClass1 {
private int ddi;
protected String dds;
public char ddc;
public DerivedClass2(int ddin, String ddstr, char ddch) {
super(ddin + 100, ddstr + "BaseClass", ddch);
this.ddi = ddin;
this.dds = ddstr;
this.ddc = ddch;
}
public String getStringValue() {
return dds;
}
public void setStringValue(String str) {
this.dds = str;
}
@Override
public String out() {
return "The content of BaseClass is " + super.getIntValue() + super.bc
+ super.bs + "/n" + "The content of DerivedClass is "
+ this.ddi + this.dds + this.ddc;
}
}
public class TestingReflection {
public static void main(String[] args) {
// System.out.println("***showFieldsInfo()***");
// showFieldsInfo();
// System.out.println("***operateFieldValue()***");
// operateFieldValue();
// System.out.println("***showMethodInfo()***");
// showMethodInfo();
// System.out.println("***invokeMethod()***");
// invokeMethod();
// System.out.println("***showConstructorInfo()***");
// showConstructorInfo();
System.out.println("***dynamicArray()***");
dynamicArray();
}
@SuppressWarnings("unchecked")
public static void showFieldsInfo() {
try {
Class cls = Class.forName("com.gaoqian.reflection.DerivedClass2");
System.out.println("---getDeclaredFields()---");
Field[] declaredfieldlist = cls.getDeclaredFields();
for (int i = 0; i < declaredfieldlist.length; i++) {
Field fld = declaredfieldlist[i];
System.out.println("name = " + fld.getName());
System.out.println("decl class = " + fld.getDeclaringClass());
System.out.println("type = " + fld.getType());
System.out.println("GenericType = " + fld.getGenericType());
int mod = fld.getModifiers();
System.out.println("modifiers = " + Modifier.toString(mod));
System.out.println("isEnumConstant = " + fld.isEnumConstant());
System.out.println("isSynthetic = " + fld.isSynthetic());
System.out.println("-----");
}
System.out.println("---getFields()---");
Field[] fieldlist = cls.getFields();
for (int i = 0; i < fieldlist.length; i++) {
Field fld = fieldlist[i];
System.out.println("name = " + fld.getName());
System.out.println("decl class = " + fld.getDeclaringClass());
System.out.println("type = " + fld.getType());
System.out.println("GenericType = " + fld.getGenericType());
int mod = fld.getModifiers();
System.out.println("modifiers = " + Modifier.toString(mod));
System.out.println("isEnumConstant = " + fld.isEnumConstant());
System.out.println("isSynthetic = " + fld.isSynthetic());
System.out.println("-----");
}
} catch (Throwable e) {
System.err.println(e);
}
}
@SuppressWarnings("unchecked")
public static void operateFieldValue() {
try {
Class cls = Class.forName("com.gaoqian.reflection.DerivedClass2");
Class partypes[] = new Class[3];
partypes[0] = Integer.TYPE;
partypes[1] = String.class;
partypes[2] = Character.TYPE;
Constructor ct = cls.getConstructor(partypes);
System.out.println("ct.class=" + ct.getDeclaringClass());
Type[] para = ct.getGenericParameterTypes();
for (Type type : para) {
System.out.println("ct.constructor(type)=" + type);
}
Class[] para2 = ct.getParameterTypes();
for (Class type : para2) {
System.out.println("ct.constructor(Class)=" + type);
}
System.out.println("ct.getName()=" + ct.getName());
System.out.println("ct.isSynthetic()=" + ct.isSynthetic());
System.out.println("ct.isVarArgs()=" + ct.isVarArgs());
Object arglist[] = new Object[3];
arglist[0] = new Integer(37);
arglist[1] = new String("operateFieldValue");
arglist[2] = new Character('z');
// Object retobj = ct.newInstance(arglist);
DerivedClass2 retobj = (DerivedClass2) ct.newInstance(arglist);
System.out.println("public filed of DericedClass is " + retobj.ddc);
// // envokeMethod2(retobj);
// setFieldValue(cls, retobj, "d", new Double(3.0));
setFieldValue(cls, retobj, "dds", "this is string");
setFieldValue(cls, retobj, "ddi", 5);
setFieldValue(cls, retobj, "ddc", 'a');
// // setFieldValue(cls,retobj,"i",7);//you can set the value for a
// // final field
showFieldsInfo();
} catch (Throwable e) {
System.err.println(e);
}
}
/**
* set value of field
*/
@SuppressWarnings("unchecked")
public static void setFieldValue(Class cls, Object instance,
String fieldName, Object value) {
System.out.println("=======================");
try {
// Class cls = Class.forName("elang.jdk6.reflect.ReflectExp");
// Field field = cls.getField(fieldName);//only return public field
Field field = cls.getDeclaredField(fieldName);
/*
* If the modifiers of field is private and without using
* field.setAccessible(true), so there will throw an
* IllegalAccessException.
*/
// If the field is static, field.get() works fine.
field.setAccessible(true);
Object val = field.get(instance);
System.out.println(fieldName + "=" + val);
System.out.println("set new value for " + fieldName);
System.out.println("isaccessible=" + field.isAccessible());
field.set(instance, value);
val = field.get(instance);
System.out.println(fieldName + "=" + val);
} catch (Throwable e) {
System.err.println(e);
}
}
@SuppressWarnings("unchecked")
public static void showMethodInfo() {
try {
Class cls = Class.forName("com.gaoqian.reflection.DerivedClass2");
Method methlist[] = cls.getDeclaredMethods();
for (int i = 0; i < methlist.length; i++) {
Method m = methlist[i];
System.out.println("name = " + m.getName());
System.out.println("decl class = " + m.getDeclaringClass());
System.out.println("getParameterTypes()");
Class pvec[] = m.getParameterTypes();
for (int j = 0; j < pvec.length; j++)
System.out.println("param #" + j + " " + pvec[j]);
System.out.println("getGenericParameterTypes()");
Type pvec2[] = m.getGenericParameterTypes();
for (int j = 0; j < pvec2.length; j++)
System.out.println("param 2#" + j + " " + pvec2[j]);
System.out.println("getExceptionTypes()");
Class evec[] = m.getExceptionTypes();
for (int j = 0; j < evec.length; j++)
System.out.println("exc #" + j + " " + evec[j]);
System.out.println("getGenericExceptionTypes()");
Type evec2[] = m.getGenericExceptionTypes();
for (int j = 0; j < evec2.length; j++)
System.out.println("exc 2#" + j + " " + evec2[j]);
System.out.println("return type = " + m.getReturnType());
System.out.println("getGenericReturnType = "
+ m.getGenericReturnType());
System.out.println("getModifiers = "
+ Modifier.toString(m.getModifiers()));
System.out.println("isBridge = " + m.isBridge());
System.out.println("isSynthetic = " + (m.isSynthetic()));
System.out.println("isVarArgs = " + (m.isVarArgs()));
System.out.println("-----");
}
} catch (Throwable e) {
System.err.println(e);
}
}
@SuppressWarnings("unchecked")
public static void invokeMethod() {
try {
Class cls = Class.forName("com.gaoqian.reflection.DerivedClass2");
Class partypes[] = new Class[1];
partypes[0] = String.class;
Method setmeth = cls.getMethod("setStringValue", partypes);
DerivedClass2 methobj = new DerivedClass2(10, "initialize", 'w');
Object arglist[] = new Object[1];
arglist[0] = "new string of invokeMethod";
//set new value of string
Object retsetobj = setmeth.invoke(methobj, arglist);
if(null == retsetobj){
System.out.println("the return value of setStringValue() is null");
}
Class partypesget[] = new Class[0];
Object arglistget[] = new Object[0];
Method getmeth = cls.getMethod("getStringValue", partypesget);
Object retgetobj = getmeth.invoke(methobj, arglistget);
//not commend
// Method getmeth = cls.getMethod("getStringValue", null);
// Object retgetobj = getmeth.invoke(methobj, null);
String retval = (String) retgetobj;
System.out.println("the return value of getStringValue() is " + retval);
} catch (Throwable e) {
System.err.println(e);
}
}
@SuppressWarnings("unchecked")
public static void showConstructorInfo() {
try {
Class cls = Class.forName("com.gaoqian.reflection.DerivedClass2");
Constructor ctorlist[] = cls.getDeclaredConstructors();
for (int i = 0; i < ctorlist.length; i++) {
Constructor ct = ctorlist[i];
System.out.println("name = " + ct.getName());
System.out.println("decl class = " + ct.getDeclaringClass());
System.out.println("ct.getModifiers()="
+ Modifier.toString(ct.getModifiers()));
System.out.println("ct.isSynthetic()=" + ct.isSynthetic());
System.out.println("ct.isVarArgs()=" + ct.isVarArgs());
System.out.println("getParameterTypes()");
Class pvec[] = ct.getParameterTypes();
for (int j = 0; j < pvec.length; j++)
System.out.println("param #" + j + " " + pvec[j]);
System.out.println("getExceptionTypes()");
Class evec[] = ct.getExceptionTypes();
for (int j = 0; j < evec.length; j++)
System.out.println("exc #" + j + " " + evec[j]);
System.out.println("getGenericParameterTypes()");
Type[] para = ct.getGenericParameterTypes();
for (Type type : para) {
System.out.println("ct.GenericParameterTypes=" + type);
}
System.out.println("getGenericExceptionTypes()");
Type evec2[] = ct.getGenericExceptionTypes();
for (int j = 0; j < evec2.length; j++)
System.out.println("exc 2#" + j + " " + evec2[j]);
System.out.println("-----");
}
} catch (Throwable e) {
System.err.println(e);
}
}
@SuppressWarnings("unchecked")
public static void dynamicArray() {
try {
// single dimension
Class cls = Class.forName("java.lang.String");
Object arr = Array.newInstance(cls, 10);
Array.set(arr, 5, "this is a test");
String s = (String) Array.get(arr, 5);
System.out.println(s);
System.out.println("length=" + ((String[]) arr).length);
System.out.println("length=" + Array.getLength(arr));
// Multiple dimension
int dims[] = new int[] { 5, 10, 15 };
Object arrM = Array.newInstance(Integer.TYPE, dims);// create
// 3*10*15
// dimension
// array
Object arrobj = Array.get(arrM, 3);
Class cls2 = arrobj.getClass().getComponentType();
System.out.println(cls2.toString());
arrobj = Array.get(arrobj, 5);
Array.setInt(arrobj, 10, 37);
int arrcast[][][] = (int[][][]) arrM;
System.out.println(arrcast[3][5][10]);
} catch (Throwable e) {
System.err.println(e);
}
}
}