黑马程序员技术交流社区

标题: 构造函数的反射,为什么会有异常? [打印本页]

作者: Rockray    时间: 2014-4-1 13:10
标题: 构造函数的反射,为什么会有异常?
本帖最后由 Rockray 于 2014-4-1 13:39 编辑

请看下面代码:
  1. import java.lang.reflect.*;

  2. public class Test5{
  3.         public static void main(String[] args) throws Exception{
  4.                 Constructor cons = Person.class.getConstructor();
  5.         }
  6. }

  7. class Person {
  8.         private String name;
  9.         private int age;
  10.         
  11.         Person(){
  12.         }
  13.         
  14.         Person(String name, int age){
  15.                 this.name = name;
  16.                 this.age = age;
  17.         }
  18.         
  19.         public String getName() {
  20.                 return name;
  21.         }
  22.         public void setName(String name) {
  23.                 this.name = name;
  24.         }
  25.         public int getAge() {
  26.                 return age;
  27.         }
  28.         public void setAge(int age) {
  29.                 this.age = age;
  30.         }
  31. }
复制代码

编译通过,运行时会抛出 NoSuchMethodException异常


请问怎么解决啊?

作者: osully    时间: 2014-4-1 13:32
这么说吧 直接getConstructor  只能对有public 修饰的
你可以换成 getDeclaredConstructor , 这是无视修饰符,private都可以
作者: Rockray    时间: 2014-4-1 13:39
已经解决了
作者: Rockray    时间: 2014-4-1 13:40
osully 发表于 2014-4-1 13:32
这么说吧 直接getConstructor  只能对有public 修饰的
你可以换成 getDeclaredConstructor , 这是无视修饰 ...

对,正解,嘿嘿
多谢!
作者: 孔丽阁    时间: 2014-4-1 14:15
你的person类不是public修饰的,getConstructor只能得到public修饰的构造方法。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2