![](/img/trans.png)
[英]How do I implement a method that returns in Java without knowing what object type I'm returning?
[英]Knowing what the contents of variables are going to be, how do I determine what to place inside the <> to eliminate “raw type” warnings?
我正在開發一個利用進化算法的程序。 該程序是在引入Java泛型之前編寫的。 我獲得的許多任務之一是刪除該舊代碼正在生成的“原始類型”警告。
我看了幾本Java參考書,並閱讀了有關刪除這些類型警告的所有問題的答案,但是沒有找到我想要的東西。 我不能簡單地添加?? 除非聲明是唯一有效的解決方案,否則對變量聲明使用通配符刪除警告。
這是發出警告的示例代碼片段。 知道發出“原始類型”警告的三個變量的內容將是什么,我如何確定在<>中放置什么以消除警告?
提前致謝。
/**
* 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
它也不會返回Class<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);
無需創建額外的數組,這些方法采用逗號分隔的事物列表(變量參數)。 您也不需要指定forName("java.lang.String")
因為您可以在此處使用實際的類型。 而且,由於您似乎知道類型,因此可以使用getConstructor
方法,而不希望第一個構造函數是正確的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.