Java反射详解(Spring配置)

1. 反射原理

a).运行时通过 Class c = Class.forName("com.hua.xx.DynTest")加载类文件
b).通过 DynTest t = c.newInstance()生成实例
c).通过 class.getMethod方法获取对应的method
d).method.invoke(t, args)调用方法

public class ReflectTest {
    public void sayHello( String ss ){
        System.out.println(ss);
    }

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        //加载class
        Class<?> c = Class.forName("ReflectTest");
        //实例化
        Object service = c.newInstance();
        //获取方法, 需要执行参数,处理同方法名时的多态情况
        Method method = c.getMethod("sayHello",String.class);
        //调用方法
        method.invoke(service,"zzzzzzz");
        
        Method[] methods = c.getMethods();
        for (Method method2 : methods) {
        	System.out.println(method2.getName());
        	System.out.println(method2.getGenericReturnType());
        	Type[] types =  method2.getGenericParameterTypes();
        	for (Type type : types) {
        		//获取参数类型
				System.out.println(type.getTypeName());
			}
        	
        	System.out.println("
");
		}
    }
}

2. getMethod--获取方法列表

//方法, 几乎可以还原一个class的原貌,除了class引用的其它classes(需要记录下所有入参和返回值的类型,加以剔除)
Method[] methods = c1.getMethods();
System.out.println(method.getName());
System.out.println(method.getGenericParameterTypes().length);
System.out.println(method.getGenericReturnType());

3. newInstance -- 构造函数

a). 无入参的构造函数
    Class c = Class.forName("DynTest");
    obj = c.newInstance();
b). 带入参的构造函数 (先获得指定的constructor)
    Class c = Class.forName("DynTest");
    Class[] pTypes = new Class[] { double.class, int.class };
    Constructor ctor = c.getConstructor(pTypes);    //指定的构造函数
    Object[] arg = new Object[] {3.14159, 125}; //自变量
    Object obj = ctor.newInstance(arg);
c). 多参数的方法
	Class ptypes[] = new Class[2];
	ptypes[0] = Class.forName("java.lang.String");
	ptypes[1] = Class.forName("java.util.Hashtable");
	Method m = c.getMethod("func",ptypes);

4. invoke -- 调用方法

//先获取方法,组装入参,再实例,调用
Test obj = new Test();
Object args[] = new Object[2];
arg[0] = new String("Hello,world");
arg[1] = null;
Object r = m.invoke(obj, arg);

    Object r = m.invoke(null, arg);    //如果被调用方法是static,则第一个参数null

5. 运行时变更fields内容

	//先获取field,再示例,再修改
	public class Test {
		public double d;
		public static void main(String args[])
		{
			Class c = Class.forName("Test");
			Field f = c.getField("d"); //指定field 名称
			Test obj = new Test();
			System.out.println("d= " + (Double)f.get(obj));
			f.set(obj, 12.34);
			System.out.println("d= " + obj.d);
		}
	}
原文地址:https://www.cnblogs.com/Desneo/p/7228644.html