java 反射机制学习(一) (四)

2014-11-24 11:54:51 · 作者: · 浏览: 47
第一个getConstructor返回一个 Constructor 对象,它反映此 Class 对象所表示的类的指定公共构造方法。
第二个getDeclaredConstructor返回一个 Constructor 对象,该对象反映此 Class 对象所表示的类或接口的指定构造方法。
第三个getConstructors 返回一个包含某些 Constructor 对象的数组,这些对象反映此 Class 对象所表示的类的所有公共构造方法。
第四个返回 getDeclaredConstructors 对象的一个数组,这些对象反映此 Class 对象表示的类声明的所有构造方法。
[java]
import java.io.IOException;
import java.lang.reflect.Constructor;
/**
* 获取指定类的构造器相关信息
* @author 胡汉三
*/
public class ConstructorTest {
private int i;
private double j;
//默认的构造器
public ConstructorTest(){}
//重载的构造器
public ConstructorTest(int i , double j) throws IOException{
this.i=i;
this.j=j;
}
/**
* @param args
*/
public static void main(String[] args)throws Exception {
//得到本类的类对象
Class cls = Class.forName("com.test.hzw.f.ConstructorTest");
//取得所有在本类声明的构造器
Constructor[] cs = cls.getDeclaredConstructors();
//遍历
for (Constructor c : cs) {
//构造器名称
System.out.println("构造器名="+c.getName());
//构造器声明所在的类
System.out.println("其声明的类="+c.getDeclaringClass());
//取得参数的类型集合
Class[] ps = c.getParameterTypes();
//遍历参数类型
for (int i = 0; i < ps.length; i++) {
System.out.println("参数类型"+i+"="+ps[i]);
}
//取得异常类型集合
Class[] es =c.getExceptionTypes();
//遍历异常类型
for (int i = 0; i < es.length; i++) {
System.out.println("异常类型"+i+"="+es[i]);
}
//结束一层循环标志
System.out.println("-------------------------");
}
}
}
import java.io.IOException;
import java.lang.reflect.Constructor;
/**
* 获取指定类的构造器相关信息
* @author 胡汉三
*/
public class ConstructorTest {
private int i;
private double j;
//默认的构造器
public ConstructorTest(){}
//重载的构造器
public ConstructorTest(int i , double j) throws IOException{
this.i=i;
this.j=j;
}
/**
* @param args
*/
public static void main(String[] args)throws Exception {
//得到本类的类对象
Class cls = Class.forName("com.test.hzw.f.ConstructorTest");
//取得所有在本类声明的构造器
Constructor[] cs = cls.getDeclaredConstructors();
//遍历
for (Constructor c : cs) {
//构造器名称
System.out.println("构造器名="+c.getName());
//构造器声明所在的类
System.out.println("其声明的类="+c.getDeclaringClass());
//取得参数的类型集合
Class[] ps = c.getParameterTypes();
//遍历参数类型
for (int i = 0; i < ps.length; i++) {
System.out.println("参数类型"+i+"="+ps[i]);
}
//取得异常类型集合
Class[] es =c.getExceptionTypes();
//遍历异常类型
for (int i = 0; i < es.length; i++) {
System.out.println("异常类型"+i+"="+es[i]);
}
//结束一层循环标志
System.out.println("-------------------------");
}
}
}我的com.test.hzw.bean.test_user类代码
[java]
/**
* 用户类
* @author 胡汉三
*
*/
public class test_user extends Test{
private int id ; //用户编号(自增)
private String name; //用户名
private String pass; //密码
private int type; //类型
public String s="";
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName