- 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};
- //Class[] argTypes = new Class[]{Class.forName("java.lang.String"),Class.forName("java.lang.Integer")};
- 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();
- }
- }
- }
- package tw.com.javasorld;
- public class Person {
- private int age;
- private String name;
- private int total;
- public Person(){
- super();
- total++;
- }
- public 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类中的构造方法改为public
反射里面的错误.
最新推荐文章于 2022-01-24 16:17:51 发布