日期:2014-05-20  浏览次数:20801 次

关于class.forNname
我最近在看think   in   java,里面第11章介绍的东西看起来很吃力,我想问一下,class到底是什么?和String似的,也是一种类型马?这种类型有什么用?

import   java.util.*;

class   Pet   {}
class   Dog   extends   Pet   {}
class   Pug   extends   Dog   {}
class   Cat   extends   Pet   {}
class   Rodent   extends   Pet   {}
class   Gerbil   extends   Rodent   {}
class   Hamster   extends   Rodent   {}

class   Counter   {   int   i;   }

public   class   PetCount   {
    static   String[]   typenames   =   {
        "Pet ",   "Dog ",   "Pug ",   "Cat ",
        "Rodent ",   "Gerbil ",   "Hamster ",
    };
    public   static   void   main(String[]   args)   {
        Vector   pets   =   new   Vector();
        try   {
            Class[]   petTypes   =   {
                Class.forName( "c11.petcount.Dog "),
                Class.forName( "c11.petcount.Pug "),
                Class.forName( "c11.petcount.Cat "),
                Class.forName( "c11.petcount.Rodent "),
                Class.forName( "c11.petcount.Gerbil "),
                Class.forName( "c11.petcount.Hamster "),
            };
            for(int   i   =   0;   i   <   15;   i++)
                pets.addElement(
                    petTypes[
                        (int)(Math.random()*petTypes.length)]
                        .newInstance());
        }   catch(InstantiationException   e)   {}
            catch(IllegalAccessException   e)   {}
            catch(ClassNotFoundException   e)   {}
        Hashtable   h   =   new   Hashtable();
        for(int   i   =   0;   i   <   typenames.length;   i++)
            h.put(typenames[i],   new   Counter());
        for(int   i   =   0;   i   <   pets.size();   i++)   {
            Object   o   =   pets.elementAt(i);
            if(o   instanceof   Pet)
                ((Counter)h.get( "Pet ")).i++;
            if(o   instanceof   Dog)
                ((Counter)h.get( "Dog ")).i++;
            if(o   instanceof   Pug)