首页 / JAVA / 在Java中使用反射
在Java中使用反射
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了在Java中使用反射,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2004字,纯文字阅读大概需要3分钟。
内容图文
![在Java中使用反射](/upload/InfoBanner/zyjiaocheng/804/b2a049a9212a4531bdabae6cd199b970.jpg)
我需要一些反思的帮助,因为我不能按照我想要的方式使我的代码工作.
我有以下内容:
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();
}
我一直在阅读很多关于反思的内容,我似乎无法做到这一点,你能帮助我吗?
解决方法:
我认为你应该依赖这样一个事实:你的两个类实际上都是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();
}
内容总结
以上是互联网集市为您收集整理的在Java中使用反射全部内容,希望文章能够帮你解决在Java中使用反射所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。