使用 JAVA 类反射机制 : Class, Constructor, and newInstance

最近在项目中遇到一个问题,要求程序在 runtime 阶段动态创建一个类的实例。很自然的便想到用 JAVA 类反射机制,下面是
一个简单例子,来说明应用方法。本例中使用 Constructor 动态获取类的含参构造方法。

 

================================ MainClass ================================================
package com.zxn.example;

import java.lang.reflect.Constructor;

public class MainClass
{
  public static void main(String[] args)
  {
     try
     {
        // find the class and the constructor
        Class cls = Class.forName("com.zxn.example.MyClass");
        Class[] paramDef = new Class[]{ String.class, String.class };
        Constructor constructor = cls.getConstructor( paramDef );
      
        // create a new instance by using the constructor
        Object[] params = new Object[]{ "userName", "password" };
        MyClass clsInstance = (MyClass)constructor.newInstance(params);
      
        // call the test() method of the class
        clsInstance.test();
     }
     catch (Exception e)
     {
         System.out.println(e.getMessage());
     }
  }
}

 

================================ MyClass ================================================
package com.zxn.example;

public class MyClass
{
  public MyClass()
  {
     System.out.println("MyClass() is getting created...");
  }

  public MyClass(String a, String b)
  {
    System.out.println("MyClass(String a, String b) is getting created...");
  }
 
  public void test()
  {
    System.out.println("test() method is getting called...");
  }
}

 

程序运行结果:
 MyClass(String a, String b) is getting created...
 test() method is getting called...

 

你可能感兴趣的:(使用 JAVA 类反射机制 : Class, Constructor, and newInstance)