1.开篇

     Java反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为Java语言的反射机制。

2.反射测试类


package reflectDemo;

public class test {

public test()
{
System.out.println("constract");
}
public test(String str,int type)
{
System.out.println("str:"+str+"type:"+type);
}
public int id;
public String name;
public void printName()
{
System.out.print("dirk.wang");
}
public static void printlol()
{
System.out.print("king.qwiner");
}

private void privateFun(String key)
{
System.out.println(key);
}

public void publicfun(String key)
{
System.out.println(key);
}
}


3.通过反射调用类


package reflectDemo;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class reflectClass {

public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, Exception, SecurityException, IllegalArgumentException, InvocationTargetException {
// TODO Auto-generated method stub
reflect();

}

public static void reflect() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException
{
//获取类
Class c=Class.forName("reflectDemo.test");
// 实例化默认无参数的构造函数
Object obj =c.newInstance();
//获取类中所有的方法(不包括私有)
Method[] m =c.getMethods();
for (Method method : m) {
System.out.println(method);
}
//获取所有方法包括私有方法
Method[] all=c.getDeclaredMethods();
for (Method method : all) {
System.out.println(method);
}
//获取类中某个指定的方法(指定方法名称和参数类型)
Method fun=c.getMethod("printlol");
//调用无参数的方法
fun.invoke(obj);
//获取有参数的方法
Method paramerfun=c.getMethod("publicfun", String.class);
// 调用有参数的方法
paramerfun.invoke(obj, "dirk.wang_paramerfun");
// 获取类中的字段(不包括私有的字段)
Field[] fields=c.getFields();
for (Field field : fields) {
System.out.println(field);
}
// 获取指定字段并且赋值
Field field1=c.getField("id");
field1.set(obj, 2017);
System.out.println(field1.get(obj));

//实例化有参数的构造函数
Class cl=Class.forName("reflectDemo.test");
//创建有参数的构造函数
Constructor ct=cl.getConstructor(String.class,int.class);
// 实例化构造函数
test t=(test)ct.newInstance("dirk",2017);
t.printlol();

}
}