Java 知道变量的内容将是什么,如何确定在<&燃气轮机;消除;“原始类型”;警告?
我正在开发一个利用进化算法的程序。这个程序是在引入Java泛型之前编写的。我得到的众多任务之一是删除此遗留代码产生的“原始类型”警告 我看了几本Java参考书,阅读了关于删除这些类型警告的所有问题的答案,但还没有找到我想要的。我不能简单地添加?变量声明的通配符,以删除警告,除非这是唯一有效的解决方案 下面是发出警告的代码片段示例。知道发出“原始类型”警告的三个变量的内容将是什么,我如何确定在中放置什么以消除警告 提前谢谢Java 知道变量的内容将是什么,如何确定在<&燃气轮机;消除;“原始类型”;警告?,java,generics,warnings,Java,Generics,Warnings,我正在开发一个利用进化算法的程序。这个程序是在引入Java泛型之前编写的。我得到的众多任务之一是删除此遗留代码产生的“原始类型”警告 我看了几本Java参考书,阅读了关于删除这些类型警告的所有问题的答案,但还没有找到我想要的。我不能简单地添加?变量声明的通配符,以删除警告,除非这是唯一有效的解决方案 下面是发出警告的代码片段示例。知道发出“原始类型”警告的三个变量的内容将是什么,我如何确定在中放置什么以消除警告 提前谢谢 /** * Uses the information from the
/**
* Uses the information from the configuration file to instantiate
* the right classes for the environment, statistics, algorithm slots
*/
private void reificate() {
try{
Raw type warning --> Class c = null;
Raw type warning --> Class params1 [] = new Class[1];
Raw type warning --> java.lang.reflect.Constructor cons = null;
Object [] params2 = new Object[1];
// Instantiating a configuration object
c = Class.forName(cfgSB.toString());
params1[0] = Class.forName("java.lang.String");
cons = c.getConstructor(params1);
params2[0] = new String(cfgFileName);
cfg = cons.newInstance(params2);
(The following code will require additional Class type variables to be declared, but if I can
learn how to eliminate the warnings above, I’ll know how to declare the new variables properly.)
// Instantiating an environment
c = Class.forName(envSB.toString());
params1[0] = Class.forName("jade.core.Config");
cons = c.getConstructors()[0];
params2[0] = cfg;
env = cons.newInstance(params2);
// Instantiating an Algo object to run
c = Class.forName(algSB.toString());
cons = c.getConstructors()[0];
params2[0] = cfg;
alg = (jade.core.EvolAlgo)cons.newInstance(params2);
// Creating statistics object and attaching it to cfg
// This has to be done last since statistics constructor is
// going to refer to the population of Algo via a local attribute C
c = Class.forName(staSB.toString());
cons = c.getConstructors()[0];
params2[0] = cfg;
sta = (jade.stats.Statistics)cons.newInstance(params2);
// ********************* end of snippet **************************//
Class.forName()
返回Class
,请参阅
即使指定了java.lang.String
,它也不能返回类,因为在编译时字符串名和实际类之间没有映射
这同样适用于构造函数、参数。。如果您有实际的运行时类型(例如,可通过String.class
获得),则只能指定具体的类类型
我大概会这样做:
jade.core.Config cfg = (jade.core.Config) Class.forName(cfgSB.toString())
.getConstructor(String.class)
.newInstance(cfgFileName);
// not sure what type that is..
Object env = Class.forName(envSB.toString())
.getConstructor(jade.core.Config.class)
.newInstance(cfg);
jade.core.EvolAlgo alg = (jade.core.EvolAlgo) Class.forName(algSB.toString)
.getConstructor(jade.core.Config.class)
.newInstance(cfg);
jade.stats.Statistics sta = (jade.stats.Statistics) Class.forName(staSB.toString())
.getConstructor(jade.core.Config.class)
.newInstance(cfg);
不需要创建额外的数组,这些方法采用逗号分隔的事物列表(varargs)。您也不需要指定forName(“java.lang.String”)
,因为您可以在这里使用实际类型。由于您似乎知道类型,因此可以使用getConstructor
方法,而不是希望第一个构造函数是正确的