在Java中,Class类提供了许多方法来获取类的元数据,包括方法信息。以下是一些常用的方法:
getDeclaredMethods(): 返回一个包含所有声明的方法(包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法)的数组。Class<?> clazz = MyClass.class;
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
System.out.println(method.getName());
}
getDeclaredMethod(String name, Class<?>... parameterTypes): 返回一个特定的声明方法,根据方法名和参数类型。如果找不到该方法,则抛出NoSuchMethodException异常。Class<?> clazz = MyClass.class;
try {
Method method = clazz.getDeclaredMethod("myMethod", String.class, int.class);
System.out.println(method.getName());
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
getMethods(): 返回一个包含所有公共方法的数组,包括继承的方法。Class<?> clazz = MyClass.class;
Method[] methods = clazz.getMethods();
for (Method method : methods) {
System.out.println(method.getName());
}
getMethod(String name, Class<?>... parameterTypes): 返回一个特定的公共方法,根据方法名和参数类型。如果找不到该方法,则抛出NoSuchMethodException异常。Class<?> clazz = MyClass.class;
try {
Method method = clazz.getMethod("myPublicMethod", String.class, int.class);
System.out.println(method.getName());
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
注意:在使用这些方法时,可能需要处理SecurityException异常。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。