package com.itheima;
public class Person{
private String name;
private int age;
Person(){
}
Person(String name,int age){
super();
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;
}
}
package com.itheima;
import java.lang.reflect.*;
public class Test7 {
public static void main(String[] args){
try{
//创建Person类字节码对象
Class<Person> c = Person.class;
System.out.println(c.getName());
//通过字节码得到Person的有参构造函数,创建它的实例对象,并进行初始化
Person person = c.getConstructor(String.class, int.class).newInstance("zhangsan",25);
//使用反射获得名为setName的方法,并给这个方法传递参数进行变量赋值
Method setNameMethod = c.getMethod("setName", String.class);
setNameMethod.invoke(person, "lisi");
//获取名为“age”的属性,并用暴力反射对该字段进行设置。
Field fieldAge = c.getDeclaredField("age");
//取消fieldAge字段的权限检查
fieldAge.setAccessible(true);
//把person对象的fieldAge字段值设置为30
fieldAge.set(person, 30);
//5、打印name和age的值
System.out.println("name=" + person.getName());
System.out.println("age=" + person.getAge());
}
catch(Exception e){
e.printStackTrace();
}
}
}
很郁闷!为什么总出现这种问题,各位大神!!
java.lang.NoSuchMethodException: com.itheima.Person.<init>(java.lang.String, int)
at java.lang.Class.getConstructor0(Class.java:2706)
at java.lang.Class.getConstructor(Class.java:1657)
at com.itheima.Test7.main(Test7.java:18);
|