温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java Class类如何获取方法信息

发布时间:2025-06-09 22:33:54 来源:亿速云 阅读:114 作者:小樊 栏目:编程语言

在Java中,Class类提供了许多方法来获取类的元数据,包括方法信息。以下是一些常用的方法:

  1. getDeclaredMethods(): 返回一个包含所有声明的方法(包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法)的数组。
Class<?> clazz = MyClass.class;
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
    System.out.println(method.getName());
}
  1. 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();
}
  1. getMethods(): 返回一个包含所有公共方法的数组,包括继承的方法。
Class<?> clazz = MyClass.class;
Method[] methods = clazz.getMethods();
for (Method method : methods) {
    System.out.println(method.getName());
}
  1. 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异常。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手