Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.
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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The arguments to getDeclaredConstructor are the types of the parameters for the constructor. 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.

Based on your Person class, you might want something like

personClass.getDeclaredConstructor(String.class, int.class);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading