NOTICE: This version of the NSF Unidata web site (archive.unidata.ucar.edu) is no longer being updated.
Current content can be found at unidata.ucar.edu.

To learn about what's going on, see About the Archive Site.

RE: DisplayRealType ClassCastException

> > Why is it that these work:
> >
> > ScalarType type = (ScalarType)
> ScalarType.getScalarTypeByName("XAxis");
> > RealType type   = (RealType)
> ScalarType.getScalarTypeByName("XAxis");
> >
> > but
> >
> > DisplayRealType type = (DisplayRealType)
> > ScalarType.getScalarTypeByName("XAxis");
> >
> > gives:
> >
> > java.lang.ClassCastException: visad.RealType
> >
> > Is this a bug or a feature?
>
> A feature.  DisplayRealType extends RealType but the DisplayRealType
> constructor prepends "Display" to the name String before invoking
> the RealType super constructor.  To avoid confusion, of course ;)
>
> So:
>
>     DisplayRealType type = (DisplayRealType)
>       ScalarType.getScalarTypeByName("DisplayXAxis");
>
> works.

I would answer this question in a more general way:

ScalarType.getScalarTypeByName() returns a ScalarType.

In general you cannot cast a type to its subtype, because subtypes are
subsets of types (remember your Venn diagrams!) so you are just "lucky"
in the case of

        RealType type   = (RealType) ScalarType.getScalarTypeByName("XAxis")


generally you have to do

        ScalarType st   = ScalarType.getScalarTypeByName("XAxis");
        if (st instanceof RealType)
           RealType type   = (RealType) st;

Relying on knowledge that ScalarType.getScalarTypeByName("XAxis")
returns a RealType may make your code more brittle; the method signature
is a contract only to return a ScalarType.

I'm not sure how Bill's answer fits into this "standard type theory"
answer. Is it equivalent using different language?


  • 1999 messages navigation, sorted by:
    1. Thread
    2. Subject
    3. Author
    4. Date
    5. ↑ Table Of Contents
  • Search the visad archives: