简体   繁体   English

为什么代码会抛出 NoSuchMethod 异常?

[英]Why does the code throw a NoSuchMethod Exception?

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

        try {
            constructor = personClass.getDeclaredConstructor(ReflectionAPI.Person.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]);
        }
    }

I dont know what to do I tried different things, I think the problem is the Parameter in the getDEclaredConstructor.我不知道该怎么做 我尝试了不同的方法,我认为问题出在 getDEclaredConstructor 中的参数。 Please help!请帮忙!

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Discover
public class Person {

    private String name;
    private int age;

    @PersonData(persons = {"Fritz", "Hans", "Peter"}, ageOfPersons = {69, 86, 99})
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}

Here's the Person class. I dont see whats wrong, Im still learning so please have mercy!这是人 class。我看不出有什么问题,我还在学习所以请怜悯!

The arguments to getDeclaredConstructor are the types of the parameters for the constructor. getDeclaredConstructor的 arguments 是构造函数的参数类型。 So here, your code would be looking for something like所以在这里,您的代码将寻找类似

public Person(Person arg) {
   ...
}

If your class doesn't have a constructor like that, you'll get the NoSuchMethodException .如果您的 class 没有这样的构造函数,您将得到NoSuchMethodException

Based on your Person class, you might want something like根据你的Person class,你可能想要类似的东西

personClass.getDeclaredConstructor(String.class, int.class);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM