本帖最后由 帅气的冬瓜 于 2013-12-10 10:10 编辑
import java.lang.reflect.*;
public class Test7 {
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
//初始化构造函数
//Class cla=Class.forName("com.itheima.Person");
//Person p=(Person)cla.newInstance();
Person p=Person.class.getConstructor(String.class,int.class).newInstance("wangwu",54); //这句是不是有问题,老是报错。麻烦运行一下,怎样修改
System.out.println("name:"+p.getAge()+"age:"+p.getAge());//打印属性值
Method SetNameMethod=Person.class.getMethod("setName", String.class);//获取方法
SetNameMethod.invoke(p, "zhangsan");
Method getAgeMethod=Person.class.getMethod("setAge", int.class);
getAgeMethod.invoke(p, "34");
System.out.println("name:"+p.getName()+"age="+p.getAge());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Person{
private String name;
private int age;
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;
}
public String toString()
{
return name+age;
}
}
|