我在WebApp中使用了一些Reflexion。我所試圖做的是做類型案件後動態調用一個方法 - 這也是不知道在編譯時在Java中動態轉換並調用
這裏是我的代碼的結構:
Controller (Interface with one method called 'execute()')
|
|
\|/
BaseController (Abstract Class with 1 abstr method called 'execute()')
/ \
/ _\|
/ GetCarController extends BaseController
|/_
AddCarController extends BaseController
現在我有這樣的代碼,它使用上述結構:
BaseController baseContr;
Properties prop = new Properties();
prop.load("some inputstream to config.properties");
Constructor cons = Class.forName(prop.getProperty(keyProperty)).
getConstructor(Class.forName(prop.getProperty(keyProperty)).getClass());// keyProperty is some input string from user
((XXXXXX)cons.newInstance (new Car(....)) ).execute();
如果您看到XXXXXX
其實是我想辦法把類型轉換動態。此鑄造必須找到一種方法來調用方法AddCarController
或GetCarController
我不想使用BaseController的任何一個實現直接調用方法,而是有一種方法根據prop.getProperty(keyProperty)
給出的方法進行投射。 ..
你爲什麼不只是投放到接口:使用反射和接口的更詳細的例子嗎?一旦你構建了實例,你知道它實現了接口,你可以調用execute,對吧? –
在運行時,Java將調用實現中的'execute()'方法,但在'Interface'中。但在編譯時它不會......等等,讓我看看......我會很快回複評論......我想試試 –
我剛試過它......它不工作。 你知道,Java不能在基類/接口/摘要中執行一個方法,但它只在編譯期間檢查基類和子類中的一致性 –