简体   繁体   English

在Java中使用反射

[英]Using reflection in Java

I need some help with reflection, since I can't make my code work the way I want to. 我需要一些反思的帮助,因为我不能按照我想要的方式使我的代码工作。

I have the following: 我有以下内容:

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

As you can see, I'm repeating code inside this switch/case. 如您所见,我在此开关/案例中重复代码。 I know I can do that piece of code using reflection but I can't seem to get it right. 我知道我可以使用反射来完成那段代码,但我似乎无法做到正确。

I've done the following: 我做了以下事情:

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

I've been reading a lot about reflection and I can't seem to get this right, can you please help me? 我一直在阅读很多关于反思的内容,我似乎无法做到这一点,你能帮助我吗?

In this line I need to declare a new "generic constructor" with reflection (equivalent to threads[i] = new InsertAndCommit(); ) 在这一行中,我需要声明一个带有反射的新“泛型构造函数”(相当于threads[i] = new InsertAndCommit();

If you use generics, you do not have to do that through a reflection proper, in the sense that you do not need to work with the constructor object explicitly (although Class.newInstance() and Array.newInstance() methods are part of the Java reflection API). 如果你使用泛型,你不必通过适当的反射来做到这一点,因为你不需要显式地使用构造函数对象(尽管Class.newInstance()Array.newInstance()方法是Java反射API)。

Since you have Class<T> , and because both classes have parameterless constructors, you can call clazz.newInstance() to create a new object, like this: 由于你有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;
}

Demo . 演示

I think you should be relying on the fact that both of your classes are actually subclasses of Thread (I'm assuming this as you're using start() in both cases). 我认为你应该依赖这样一个事实:你的两个类实际上都是Thread子类(我假设这是因为你在两种情况下都使用了start() )。

  • You can create an array of type Thread [] and assign any object of a subclass of Thread to it. 您可以创建一个Thread []类型的数组,并为其分配Thread子类的任何对象。
  • You don't need to look up the constructor because your the parameterless construcor can be invoked directly from the class object. 您不需要查找构造函数,因为可以直接从类对象调用无参数构造函数。
  • A constructor always gives you a single object, not an array of objects. 构造函数总是为您提供单个对象,而不是对象数组。 So you should use it only inside the loop, to create each individual thread, not to create the array. 所以你应该只在循环内部使用它来创建每个单独的线程,而不是创建数组。

So the missing piece is: 所以缺少的部分是:

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