日期:2014-05-20  浏览次数:20832 次

找不到为什么出错了
Java code
package tw.com.javasorld;

import java.lang.reflect.*;

public class TestReflection03 {
    public static void main(String[] args) {

        Class c;
        Constructor constractor;
        Object obj ;
        
        try{

            c= Class.forName("tw.com.javasorld.Person");
            
            //调用有参数的构造方法
            Class[] argTypes = new Class[]{String.class,int.class};
            constractor = c.getConstructor(argTypes);
            obj = constractor.newInstance("中国",5000);
            System.out.println(obj);
            
            //调用无参方法的构造函数
            constractor = c.getConstructor();
            obj = constractor.newInstance();
            System.out.println(obj);
            
        }catch(Exception e){
            e.printStackTrace();
        }

    }

}


Java code
package tw.com.javasorld;

public class Person {
    
    private int age;
    private String name;
    private int total;
    
    Person(){
        super();
        total++;
    }
    Person(String name,int age){
        super();
        this.name = name;
        this.age = age;
        total++;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getTotal() {
        return total;
    }
    public void setTotal(int total) {
        this.total = total;
    }
    public String toString(){
        return "Name :" +name +"\tAge :" + age;
    }

}




第一个类运行不了,总报java.lang.NoSuchMethodException: tw.com.javasorld.Person.<init>(java.lang.String, int)错..可是Person中有相应构造方法.
不知道问题处在哪了?


------解决方案--------------------
Class[] argTypes = new Class[]{Class.forName("java.lang.String"),Class.forName("java.lang.Integer")};
试试
------解决方案--------------------
构造函数声明成public的