Java编程: 类的反射(第一节)

Java编程: 类的反射(第一节

    

  第一步:加载类

       加载类以下有下几种方法:

           1,class.formName("");

           2,类名.getClass();

           3,类名.calss;

       加载类的代码实现代码如下:

        public void test(){  

                // 1.1,加载类

Class cls = Class.forName("cn.csdn.web.test.Student");

System.out.println(cls);

// 1.2、加载类

Student stu = new Student();

Class cls1 = stu.getClass();

System.out.println(cls1);

// 1.3、加载类

Class cls2 = Student.class;

System.out.println(Student.class);

}  

  第二步:解析类

          解析类有以下几种

             1,解析无参数的构造器

             2,解析有参数的构造器 

             3,解析有数组参数的构造器

             4,解析private修饰的方法

             5,解析含有两个参数的构造器

          解析类实现的代码

                1,解析无参数的构造器

  public void test() throws Exception {

// 1.1,加载类

Class cls = Class.forName("cn.csdn.web.test.Student")

// 2、通过无参数的构造器解析

Constructor constructor = cls.getConstructor(null);

// 3、创建类的实例

Student entity = (Student)constructor.newInstance(null);

// 4,对象调用方法

entity.stady();

}

                2 ,解析含有两个参数的构造器

@Test

public void test2() throws ClassNotFoundException, SecurityException,

NoSuchMethodException, IllegalArgumentException,

InstantiationException, IllegalAccessException,

InvocationTargetException {

 //加载类

Class cls = Class.forName("cn.csdn.web.test.Student");

  //通过带有参数的构造器解析

    Constructor constructor = cls.getConstructor(String.classint.class);

//创建类的实例

    Student entity = (Student) constructor.newInstance("wangli", 23);

         //对象调用方法

entity.stady();

        System.out.println(entity.getName());wangli

        System.out.println(entity.getAge());23

}

             3,解析有数组参数的构造器

@Test

public void test3() throws Exception{

     Class cls = Class.forName("cn.csdn.web.test.Student");    

    //通过带有数组参数的构造器解析

      Constructor constructor=cls.getConstructor(String[].class);

     String[] stu=new String[]{"11","22"};

      Student entity = (Student) constructor.newInstance((Object)stu);

entity.stady();

}

                4,解析private修饰的方法

public void test4()throws Exception{

     Class cls = Class.forName("cn.csdn.web.test.Student");    

     Constructor constructor =cls.getDeclaredConstructor(List.class);

     constructor.setAccessible(true);  //暴力反射

     Student entity = (Student) constructor.newInstance(new List());

     entity.stady();

}

    

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/wangliaizq10000/archive/2011/02/22/6199912.aspx

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值