[英]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.