mercredi 4 avril 2018

How to check if object which is of a sub

I have an object which is modeled as such:

public class Template {
    private Form form;
    public Form getForm() { return form; }
}

public class SubTemplate extends Template {
    private Report report;

    public Report getReport() { return report; }

}

public class AnotherSubTemplate extends Template {
    private Sheet sheet;

    public Sheet getSheet() { return sheet; }

}

My Goal:

I want to know how I can check to see if the base object I'm dealing with Template in this case, is exercising polymorphism and is actually SubTemplate, so I can retrieve the report object from it?

Here is what I mean, something like this:

main() {
    Template t = something();
    if( t.getClass().isInstance(SubTemplate.class) ) {
        Report r = ((SubTemplate) t).getReport();
    }
}

This doesn't seem to work since the condition is always false. How can I accomplish my goal?

I realize this is some what of a hack but is what I'm asking possible? If so how to?

Aucun commentaire:

Enregistrer un commentaire