Java relection
//原类
package mypackage;
public class forclass {
public static String name="xiaoMing";
public static int age=12;
public void prinfMethod()
{
System.out.println("gaowh print");
}
}
//普通方法实例化
package mypackage;
public class commonInvork {
public static void main(String[] args) {
forclass my=new forclass();
my.prinfMethod();
}
}
//For class invoke
package mypackage;
import java.lang.reflect.Field;
public class forClassInvoke{
public static void main(String args[]) throws Exception{
// Class<?> my=Class.forName("mypackage.forclass");
// newInstance of reflected class, then invoke the method of the reflected class
//this method can print all static and non static constants or methods
// forclass newobject=(forclass)my.newInstance();
// newobject.prinfMethod();
// System.out.println(newobject.age);
//
Class ownerClass = Class.forName("mypackage.forclass");
//Field[] fields= ownerClass.getDeclaredFields(), it is used to get
//all public and private constants ,but getFields is used to get only punlic constants
Field[] fields= ownerClass.getFields();
for(int i=0;i<fields.length;i++)
{
//find the filedname and field type
System.out.println("zz="+fields[i].getName()+"==>"+fields[i].getType());
}
//get the value of the static field
Field field = ownerClass.getField("name");
Object value = field.get(ownerClass);
//print value
System.out.println(value);
}
}