通过反射获取类的构造方法信息
方法 | 说明 |
---|---|
Constructor getConstructor( Class… params) | 返回该类型指定参数列表的public构造方法,构造方法的参数列表与params所指定的类型列表所匹配 |
Constructor[] getConstructors() | 返回该类型的所有public构造方法 |
Constructor getDeclaredConstructor( Class… params) | 返回该类型的指定参数列表的构造方法,访问级别不限 |
Constructor[] getDeclaredConstructors() | 返回该类型的所有构造方法,访问级别不限 |
具体的用法如下:
try {
//获取person类的信息
Class perClass= Class.forName("cn.bcsp.demo1.Person");
//调用person类中的无参构造方法创建对象
Person person=(Person) perClass.newInstance();
//调用person类中的有参构造方法创建对象
//获得person类中的一个参数的构造方法(访问权限允许的)
Constructor constructor= perClass.getConstructor(String.class);
//newInstance()执行构造方法 创建对象
Person person1=(Person)constructor.newInstance("吕老八");
//获得person类中的一个参数的构造方法(忽略访问权限)
Constructor constructor2= perClass.getDeclaredConstructor(String.class);
//即使访问权限不允许,也可以执行构造方法
constructor2.setAccessible(true);
Person person2=(Person)constructor2.newInstance("吕老八");
} catch (Exception e) {
e.printStackTrace();
}
通过反射获取类型中的方法信息
方法 | 说明 |
---|---|
Method getMethod(String name, Class… params) | 返回该实例中指定的public方法,name参数用于指定方法名称,params参数指定参数列表 |
Method[] getMethods() | 返回该实例中所有public方法 |
Method getDeclaredMethod(String name, Class… params) | 返回该实例中指定的方法,与方法的访问级别无关 |
Method[] getDeclaredMethods() | 返回该实例中的全部方法,与方法的访问级别无关 |
具体的用法如下:
try {
Class perClass= Class.forName("cn.bcsp.demo1.Person");
//获得perClass类中的getName方法(访问权限允许的)
Method getNameMethod=perClass.getMethod("getName");
//获得perClass类中的setName方法(忽略访问权限)
Method setNameMethod= perClass.getDeclaredMethod("setName",String.class);
//获得perClass类中的所有方法(访问权限允许的)
Method[] methods= perClass.getMethods();
//获得perClass类中的所有方法(忽略访问权限)
Method[] methods2= perClass.getDeclaredMethods();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch(NoSuchMethodException e){
e.printStackTrace();
}