Java反射

什么是反射?
即通过字节码文件对象去使用成员。

(1)获取字节码文件对象的三种方式:
    A:Object类的getClass()方法
    B:数据类型的静态class属性
    C:Class类的静态方法forName()

得到字节码文件对象后,我们可以通过这个对象获取类的构造方法,并创建对象,使用它的成员方法和成员变量。

举例:构造方法的遍历和调用

public class ConstructorTest {

    /**
     * @param args
     * @throws ClassNotFoundException 
     * @throws SecurityException 
     * @throws NoSuchMethodException 
     * @throws InvocationTargetException 
     * @throws IllegalArgumentException 
     * @throws IllegalAccessException 
     * @throws InstantiationException 
     */
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        // TODO Auto-generated method stub
        Class<?> a = Class.forName("com.day17.constructor.Animal");

        Constructor<?>[] con = a.getConstructors();    //获取公开的构造方法

        for (Constructor<?> co : con) {
            System.out.println(co);   //public com.day17.constructor.Animal()
        }
        System.out.println("-------------");

        Constructor<?>[] con2 = a.getDeclaredConstructors();    //获取所有的构造方法
        for (Constructor<?> co : con2) {
            System.out.println(co);        //com.day17.constructor.Animal(java.lang.String,int,java.lang.String)
                                           //public com.day17.constructor.Animal()
        }
        System.out.println("-------------");

        Constructor<Animal> dcon = (Constructor<Animal>) a.getDeclaredConstructor(String.class,int.class,String.class);
        dcon.setAccessible(true);
        Animal ni = dcon.newInstance("小狗",20,"白色");
        System.out.println(ni);
    }

}

举例:成员方法的遍历和调用(成员变量同理)

public class MethodTest {

    /**
     * @param args
     * @throws ClassNotFoundException 
     * @throws Exception 
     * @throws NoSuchMethodException 
     */
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, Exception {
        // TODO Auto-generated method stub
        Class<?> c = Class.forName("com.day17.method.Animal");
        Constructor<?> con = c.getConstructor();
        Object ni = con.newInstance();

        Method[] dm = c.getDeclaredMethods();
        for (Method method : dm) {
            System.out.println(method);
        }
        System.out.println("-----------------");

        Method dme = c.getDeclaredMethod("eat");
        System.out.println(dme);
        dme.invoke(ni);
        Method dmf = c.getDeclaredMethod("fun");
        dmf.setAccessible(true);
        dmf.invoke(ni);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值