java反射-动态的创建对象与调用方法

无参构造

  • 创建类的对象:调用Class对象的newInstance()方法

    • 必须有一个无参数的构造器

    • 类的构造器访问权限需要足够

    • Class c1 = Class.forName("com.zhou.HelloWorld");
      HelloWorld helloWorld = (HelloWorld)c1.getDeclaredConstructor().newInstance();//无参构造
      System.out.println(helloWorld);
      

有参构造

  • 通过Class类的getDeclaredConstructor取得指定形参的构造器

  • 通过构造器实例化

  • HelloWorld helloWorld2 = (HelloWorld)c1.getDeclaredConstructor(String.class,int.class).newInstance("a",1);
    System.out.println(helloWorld2);
    

反射调用普通方法

  • 通过反射调用方法,通过Method相关函数完成

  • 通过Class类的getDeclaredMethod(String name,Class... parameterTypes)方法取得一个Method对象,设置此方法操作时所需要的参数类型

  • 通过invoke方法进行调用

  • Class c1 = Class.forName("com.zhou.HelloWorld");
    //实例化
    HelloWorld helloWorld = (HelloWorld)c1.getDeclaredConstructor().newInstance();//无参构造
    //通过反射调用方法
    Method setName = c1.getDeclaredMethod("setName", String.class);
    //invoke,激活,调用类的方法
    //invoke(object,args)
    setName.invoke(helloWorld2,"asas");
    System.out.println(helloWorld2);
    
posted @ 2021-09-14 16:28  貂蝉贼6  阅读(407)  评论(0)    收藏  举报