Re: How do I retrieve the 'type' of an object



(sorry if this comes through twice -- my MUA is giving me fits)

On Sunday, June 6, 2004, at 06:32 PM, Daniel Kasak wrote:

I'm looping through a set of objects, and I want to get the type of object, ( eg GtkEntry ) and then decide what to do based on the type.
How do I do that?
eg:

    foreach my $field (@{$self->{fieldlist}}) {
                    my $widget = $self->{form}->get_widget($field);
                # Need to figure out what type of object $widget is
            }

i'm presuming you are trying to write a generic handler for a bunch of widgets in a form. for example, you have an array of widgets which may be entries for strings, or spinbuttons for numbers, or combos for enums, etc.

in that case you want to handle the number, string, and enum types differently.

what aristotle said, that you don't want to differentiate by types, is true; that breaks the ability to use subclasses of things. in this situation, though, polymorphism will require multiple inheritance, which can be a bit much work, so effectively "switch"ing on object type is a decent idea. and, of course, you use perl's "ref" operator to tell into what class an object is blessed.

*however*, in practice, you don't want to know *exactly* what type your object is; you only care if it is descended from the right type. you use "isa" for that:

   foreach my $field (@{$self->{fieldlist}}) {
       my $widget = $self->{form}->get_widget ($field);
       if ($widget->isa ('Gtk2::SpinButton')) {
          # you use spinbuttons for numbers
       } elsif ($widget->isa ('Gtk2::OptionMenu')) {
          # optionmenus are used for the enum stuff
       } elsif ($widget->isa ('Gtk2::Entry')) {
          # it's an entry, so you have a string.
       } else {
          # don't know how to handle it.
       }
   }




--
muppet <scott at asofyet dot org>




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]