繁体   English   中英

在Java中使用反射

[英]Using reflection in Java

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

我有以下内容:

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;
}

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

我做了以下事情:

 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();
            }

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

在这一行中,我需要声明一个带有反射的新“泛型构造函数”(相当于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;
}

演示

我认为你应该依赖这样一个事实:你的两个类实际上都是Thread子类(我假设这是因为你在两种情况下都使用了start() )。

  • 您可以创建一个Thread []类型的数组,并为其分配Thread子类的任何对象。
  • 您不需要查找构造函数,因为可以直接从类对象调用无参数构造函数。
  • 构造函数总是为您提供单个对象,而不是对象数组。 所以你应该只在循环内部使用它来创建每个单独的线程,而不是创建数组。

所以缺少的部分是:

Class<? extends Thread> clazz = (Class<? extends Thread>) Class.forName(testName);
Thread[] threads = new Thread[nrThreads];
for ( int i = 0; i < nrThreads; i++ ) {
    threads[i] = clazz.newInstance();
    threads[i].start();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM