Java反射

2017-09-05  本文已影响0人  空城EN

最近在研究spring框架,而spring的ioc是基于反射机制来完成的,因此先来学习下反射

  1. 使用场景
    当我们的程序在运行时,需要动态的加载一些类,而这些类可能由于之前用不到所以没有加载到jvm,而是在运行时根据需要才加载,比如,我们之前连接mysql时,都要动态的加载mysql驱动程序,这时就要用到反射。

  2. 原理机制

  1. 实现
  1. 实例
public class testReflection {

    public int age=10;
    public int getAge(){
        return age;
    }
    public int getSome(int i){
        return i;
    }

    public static void main(String[] args) throws Exception{
        Class<?> clazz=Class.forName("xy.reflection.testReflection");
        //无参方法
        Method method=clazz.getMethod("getAge");
        int i=(Integer) method.invoke(clazz.newInstance());
        System.out.println(i+"");
        //有参方法
        Method m=clazz.getMethod("getSome", int.class);
        int j=(Integer) m.invoke(clazz.newInstance(),100);
        System.out.println(j+"");
    }

    @Test
    public void testMethod() throws Exception{
        Class<?> clazz=Class.forName("xy.reflection.testReflection");
        System.out.println(clazz.getName());
       //获取对象的属性
        Field field=clazz.getDeclaredField("age");
        field.set(this,2);
        System.out.println(age+"");

    }
}
上一篇 下一篇

猜你喜欢

热点阅读