[英]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]);
}
}
我不知道该怎么做 我尝试了不同的方法,我认为问题出在 getDEclaredConstructor 中的参数。 请帮忙!
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;
}
}
这是人 class。我看不出有什么问题,我还在学习所以请怜悯!
getDeclaredConstructor
的 arguments 是构造函数的参数类型。 所以在这里,您的代码将寻找类似
public Person(Person arg) {
...
}
如果您的 class 没有这样的构造函数,您将得到NoSuchMethodException
。
根据你的Person
class,你可能想要类似的东西
personClass.getDeclaredConstructor(String.class, int.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.