反射知识1-访问构造方法
今天在家,突然想到了老师讲课没有讲到过反射机制,这是JDK1.5加入的新功能,通过反射,可以在程序中访问已经装载到JVM里的java对象描述,实现访问、检测和修改java对象本身信息的功能.
先列出来我下面写的这个小例子用到的方法
getClass():返回此 类 的运行时类
getDeclaredConstructors():获得构造方法,返回Constructor[]
isVarArgs():构造方法是否含有可变数量的参数
getParameterTypes():构造方法的入口参数类型,返回Class[]
getExceptionTypes():可能抛出的异常,返回Class[]
newInstance():表示的构造方法来创建该构造方法的声明类的新实例,我觉得这个可以想成构造方法的代替。
Example_01 Code:
public class Example_01 {String s;int i, i2, i3;private Example_01() {}protected Example_01(String s, int i) {this.s = s;this.i = i;}public Example_01(String...strings) {if(0 < strings.length) {i = Integer.valueOf(strings[0]);}if(1 < strings.length) {i2 = Integer.valueOf(strings[1]);}if(2 < strings.length) {i3 = Integer.valueOf(strings[2]);}}public void print() {System.out.println("s = " + s);System.out.println("i = " + i);System.out.println("i2 = " + i2);System.out.println("i3 = " + i3);}}import java.lang.reflect.Constructor;/** * 测试类,通过反射访问Example_01类中的所有构造方法,并将该构造方法 * 是否允许带有可变数量的参数、入口参数类型和可能抛出的异常类型输出 * @author Xue * */public class Main_01 {public static void main(String[] args) {Example_01 example = new Example_01("10", "20", "30");Class exampleC = example.getClass();//返回此 类 的运行时类//获得所有构造方法Constructor[] declaredConstructors = exampleC.getDeclaredConstructors();for(int i = 0; i <declaredConstructors.length; i++) {//遍历构造方法Constructor constructor = declaredConstructors[i];System.out.println("查看是否允许带有可变数量的参数:" + constructor.isVarArgs());System.out.println("该构造方法的入口参数依次是:");//获取所有参数类型Class[] parameterTypes = constructor.getParameterTypes();for(int j = 0; j < parameterTypes.length; j++) {System.out.println("" + parameterTypes[j]);}System.out.println("该构造方法可能抛出的异常类型为:");//获取所有可能抛出的异常Class[] exceptionTypes = constructor.getExceptionTypes();for(int j = 0; j < exceptionTypes.length; j++) {System.out.println("" + exceptionTypes[j]);}Example_01 example2 = null;while(example2 == null) {//如果访问权限是private,则抛出异常,既不允许访问try {if(i == 0) {//通过执行默认没有参数的构造方法创建对象example2 = (Example_01) constructor.newInstance();} else if(i ==1) {//通过执行有两个参数的构造方法创建对象example2 = (Example_01) constructor.newInstance("7" ,5);} else {//通过执行可变参数的构造方法来创建对象Object[] parameter = new Object[]{new String[]{"100", "200", "300"}};example2 = (Example_01) constructor.newInstance(parameter);}} catch (Exception e) {System.out.println("在创建对象的时候抛出异常,下面执行setAccessibl()方法");constructor.setAccessible(true);//更改为可访问} }}}}