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.class, int.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