arabian_albert
arabian_albert

Reputation: 708

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?

Upvotes: 0

Views: 47

Answers (1)

DennisV
DennisV

Reputation: 128

This is what instanceof is meant to do:

Template t = something();
if (t instanceof SubTemplate) {
    SubTemplate sub = (SubTemplate) t;
    sub.getReport();
}

So after checking its type, you can cast it without expecting an exception.

Note that this is usually considered a code smell, see the comments for links to more information on why this is.

Upvotes: 1

Related Questions