- public static void main(String[] args) throws Exception{
- Class c = Class.forName("cn.socket.Persion");
-
- Constructor constructor= c.getConstructor();
- Persion person1 =(Persion)constructor.newInstance();
-
- Method mothod1= person1.getClass().getMethod("setAge",int.class);
- mothod1.invoke(person1, 39);
- Method mothod2= person1.getClass().getMethod("setName",String.class );
- mothod2.invoke(person1, "lala");
- Field m1= person1.getClass().getField("age");
- System.out.println(m1.get(person1));
- Field m2= person1.getClass().getField("name");
- System.out.println(m2.get(person1));
-
-
- }
- public class Persion {
- public String name;
- public int age;
-
- public Persion(String name,int age){
- this.name=name;
- this.age=age;
- }
- public Persion(){
- }
- public void setName(String name){
- this.name=name;
- }
- public String getName(){
- return this.name;
- }
- public void setAge(int age){
- this.age=age;
- }
- public int getAge(){
- return this.age;
- }
- }
复制代码 Constructor constructor= c.getConstructor(Persion.class);//调用构造函数是传入的构造函数的参数,你这里传入的是对象。
Persion person1 =(Persion)constructor.newInstance(new Persion("bibo",21));//如果你通下面反射获取方法设置的话,这里应该调用空构造函数,所以不用赋值、
Method mothod2= person1.getClass().getMethod("setName",String.class );
mothod1.invoke(person1, "lala");//这里应该是mothod2
public Persion(){
this.name="lili";
this.age=1;
}//你通过反射获取方法设置,这里就不用设置,用一个空的构造函数。
|