You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何代码抛出NoSuchMethodException异常?请求技术帮助

解决Java反射NoSuchMethodException异常问题

问题根源

你的代码抛出异常的核心原因是:调用getDeclaredConstructor时传入的参数类型,和Person类实际构造方法的参数类型完全不匹配。

Person类定义的构造方法是:

public Person(String name, int age)

它的参数类型是String.class和int.class,但你在主方法里写的是:

constructor = personClass.getDeclaredConstructor(ReflectionAPI.Person.class);

传入的是Person类自身的Class对象,JVM找不到对应参数的构造方法,自然抛出NoSuchMethodException。

修正后的主方法代码

public static void main(String[] args) {
    Class<Person> personClass = Person.class;
    Constructor<Person> constructor;

    try {
        // 传入构造方法实际的参数类型:String和int的Class对象
        constructor = personClass.getDeclaredConstructor(String.class, int.class);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    }

    PersonData personData = constructor.getAnnotation(PersonData.class);
    String[] names = personData.persons();
    int [] ages = personData.ageOfPersons();
    for (int i = 0; i < names.length; i++) {
        System.out.println(names[i]);
        System.out.println(ages[i]);
    }
}

额外注意事项

  • getDeclaredConstructor方法的参数必须严格对应构造方法的参数类型Class对象,顺序也要和构造方法定义的一致。如果是无参构造,直接调用getDeclaredConstructor()(不带任何参数)即可。
  • 确保你的PersonData注解添加了@Retention(RetentionPolicy.RUNTIME)元注解,只有运行时保留的注解,才能通过反射获取到。如果注解只在编译期保留,constructor.getAnnotation(PersonData.class)会返回null。

内容的提问来源于stack exchange,提问作者Lenntox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 23:00:17