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

Lenntox
  • 15
  • 5

1 Answers1

1

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);
Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
  • Use Integer.TYPE, as per https://stackoverflow.com/a/3925617/681444 – racraman Jan 13 '23 at 08:55
  • 1
    @racraman That does exactly the same thing. But if you want to write an answer that's slightly different from mine, go right ahead. – Dawood ibn Kareem Jan 13 '23 at 08:56
  • 2
    @racraman according to the post that you linked: _You can also use `int.class`. It's a shortcut for `Integer.TYPE`. Therefore both ways are equally acceptable. – Thomas Kläger Jan 13 '23 at 10:02