以下代码都需要另外import一个Student类来执行
Method
以下4种方法,全部都在Class类中:
- getMethods(): 获得类的public类型的方法
取得所有public的方法,包括继承的,接口中声明的和自己定义的
- getDeclaredMethods():
取得所有当前类声明的方法,包括public,protected,默认,private四种访问权限的方法,但是不包括继承的方法
- getMethod(String name, Class[] params): 获得类的特定方法,name参数指定方法的名字,params参数指定方法的参数类型
- getDeclaredMethod(String name, Class[] params): 获得类的特定方法,name参数指定方法的名字,params参数指定方法的参数类型
Class<Student> student=Student.class;
Method[] publicMethods=student.getMethods();
for(Method method : publicMethods)
{
System.out.println(method.getName());//输出所有public方法
}
Method类的常见方法——invoke
Student student = new Student();
Class<?> Student1 = student.getClass();
try {
Method privateStudyMethod = Student1.getDeclaredMethod(
"privateStudy", int.class);
// 调用的方法是public的,就不需要进行设置
privateStudyMethod.setAccessible(true);
privateStudyMethod.invoke(student, 24);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
Field
以下2种方法,全部都在Class类中:
- Field[] getFields()
取得所有public的属性,包括继承的,接口中声明的和自己定义的 - Field[] getDeclaredFields()
取得所有当前类自己定义的属性,包括四种访问权限的
Class<Student> c=Student.class;
Field[] publicMethods1=c.getFields();
for(Field field : publicMethods1)
{
System.out.println(field.getName());//输出所有public属性
}
field类的常见方法——setAccessible
ageField.setAccessible(true);//可以操作private修饰的属性