在Java中使用反射

Sai*_*ike 4 java reflection

我需要一些反思的帮助,因为我不能按照我想要的方式使我的代码工作.

我有以下内容:

nrThreads = Utilities.getNumberOfThreads(filePath, propertiesFile);
testName = Utilities.getTestName(filePath, propertiesFile);  
System.out.println(Utilities.nowDate());
System.out.println("Inserting...");

switch (testName)
{
case "InsertAndCommit":
      final InsertAndCommit[] threads = new InsertAndCommit[nrThreads];
      for (int i = 0; i < nrThreads; i++) {
        threads[i] = new InsertAndCommit();
        threads[i].start();
      }                         
      break;            
case "CommitAfterAllInserts":
      final CommitAfterAllInserts[] threads1 = new CommitAfterAllInserts[nrThreads];
      for (int i = 0; i < nrThreads; i++) {
        threads1[i] = new CommitAfterAllInserts();
        threads1[i].start();
      }
      break;
      default: break;
}
Run Code Online (Sandbox Code Playgroud)

如您所见,我在此开关/案例中重复代码.我知道我可以使用反射来完成那段代码,但我似乎无法做到正确.

我做了以下事情:

 Class<?> clazz = Class.forName(testName);
 Constructor<?> ctor = clazz.getConstructor(String.class);
 final Object[] obj = (Object[]) ctor.newInstance(); //this line isn't right, I need to declare the "threads" array (equivalent to: final InsertAndCommit[] threads = new InsertAndCommit[nrThreads];)

            for (int i = 0; i < nrThreads; i++) {
                //In this line I need to declare a new "generic constructor" with reflection (equivalent to threads[i] = new InsertAndCommit();) 
                threads[i].start();
            }
Run Code Online (Sandbox Code Playgroud)

我一直在阅读很多关于反思的内容,我似乎无法做到这一点,你能帮助我吗?

das*_*ght 5

在这一行中,我需要声明一个带有反射的新"通用构造函数"(相当于threads[i] = new InsertAndCommit();)

如果您使用泛型,你没有这样做,通过适当的反映,因为你并不需要显式的构造函数对象的工作(虽然意义Class.newInstance()Array.newInstance()方法是Java反射API的一部分).

既然你有Class<T>,并且因为这两个类都有无参数构造函数,你可以调用clazz.newInstance()创建一个新对象,如下所示:

public <T extends Thread> T[] makeArray(Class<T> clazz, int n) throws Exception {
    T[] res = (T[]) Array.newInstance(clazz, n);
    for (int i = 0 ; i < n ; i++) {
        res[i] = clazz.newInstance();
        res[i].start();
    }
    return res;
}
Run Code Online (Sandbox Code Playgroud)

演示.