2015-05-27 53 views
1

我有三個類AbstractResumeOrchestratorPattern1orhcestratorPattern2orhcestratorJava繼承獲取基於對象類型的子類的所有方法

後兩者延伸AbstractResumeOrchestrator

AbstractResumeOrchestrator本身延伸AbstractOrchestrator

調用到AbstractOrchestrator對象execute方法調用以下提到的方法:

public abstract class AbstractResumeOrchestrator extends AbstractOrchestrator<OnboardingSessionDTO> 
{ 
    protected OrchestratorResponse execute(final OnboardingSessionDTO onboardingSessionDTO, final KVPContext kvpContext) throws Exception { 
     // based on the object's class that extends AbstractResumeOrchestrator 
     // get it's all functions - it could be pattern1 or 2 orchestator 
     Method method = Pattern1Orchestrator.class.getDeclaredMethod(); 
    } 
} 

我想基於它是否型式1或模式2的所有方法或協調器。我無法更改用於傳遞子類名的方法的參數簽名execute

我怎樣才能最有效地做到這一點?

+0

您對不在父類中的方法感興趣嗎? –

+0

是的,如果我的Orchestrator是Pattern1類型,那麼我需要pattern1的所有方法,對於pattern2也是類似的。 – pseudoCoder

+1

爲什麼不讓這個方法抽象?並在Pattern1Orchestrator和Pattern2Orchestrator中實現它,並在這些對象的實例上調用它。 –

回答

0

如果您想在​​中使用子類特定的行爲,您應該真的考慮在具有該功能的特定子類中重寫該方法。

如果您仍然想這樣做在父類(不推薦),您可以按以下使用instanceof

if(this instanceof Pattern1orhcestrator){ 
    Method method = Pattern1Orchestrator.class.getDeclaredMethod(); 
    //your logic 
} 
else if(this instanceof Pattern2orhcestrator){ 
    Method method = Pattern2Orchestrator.class.getDeclaredMethod(); 
    //your logic 
} 

的原因,它是壞主意,有這樣的父類是父類有了解所有子類和子類特定行爲,從而難以添加擴展父類的新類。

+0

這裏的問題是''你的邏輯'對於兩種情況都是一樣的。我真正需要的只是獲取對應於orchestrator的正確方法函數。像'this.class.getDeclaredMethods()'這樣的東西? – pseudoCoder

+0

可能是我沒有完全解決你的問題,但是如果它的公共或者添加任何其他的共享代碼,你可以很容易地將你的邏輯移動到if-else結尾。 'If-else'的作用等同於'this.class.getDeclaredMethods()'。希望這可以幫助。 – hitz

相關問題