欢迎来到天天文库
浏览记录
ID:8977218
大小:42.50 KB
页数:4页
时间:2018-04-13
《java编程思想-根据类型信息向容器随机创建对象》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、importjava.util.*;//(用来随机创建的)抽象基类//PetCreator.javaabstractclassPetCreator{privateRandomrand=newRandom(47);publicabstractList>types();publicPetrandomPet(){intn=rand.nextInt(types().size());//随机范围<=types容器的大小try{returntypes().get(n).newInstance();}catch(Instanti
2、ationExceptione){thrownewRuntimeException(e);}catch(IllegalAccessExceptione){thrownewRuntimeException(e);}}publicPet[]createArray(intsize){Pet[]result=newPet[size];for(inti=0;iarrayList(intsi
3、ze){ArrayListresult=newArrayList();Collections.addAll(result,createArray(size));System.out.println("已填加"+result.size()+"个种类");//根据Pet[]数组引用装入容器returnresult;}}//PetCreator的派生类//ForNameCreator.javaclassForNameCreatorextendsPetCreator{privatestaticList>
4、types=newArrayList>();privatestaticString[]typesNames={"typeinfo.pets.Mutt","typeinfo.pets.Pug","typeinfo.pets.EgyptianMau","typeinfo.pets.Manx","typeinfo.pets.Cymric","typeinfo.pets.Rat","typeinfo.pets.Mouse","typeinfo.pets.Hamster",};privatestaticvoidLoader(
5、){try{for(Stringname:typesNames)types.add((Class)Class.forName(name));}catch(ClassNotFoundExceptione){System.out.println("创建对象的Class类时出现错误");thrownewRuntimeException(e);}}static{System.out.println("开始向types容器输入各类Class类型信息");Loader();}publicList>ty
6、pes(){returntypes;}//返回对容器(类型信息类)的引用typespublicstaticvoidmain(String[]arges){newForNameCreator();}}//随机创建.javaclass随机创建{publicstaticvoidcountPets(PetCreatorcreator)//向上转型为抽象基类的引用{creator.arrayList(20);//调用基类中arrayList函数//开始真的随机创建20个宠物对象并放入容器中}publicstaticvoidmain(String[]arges){
7、//一切从这里开始countPets(newForNameCreator());//创建派生类对象调用本类静态函数}}//***********************以下的模块框架是上面的材料********************************//5层类继承的基类第一层//Individual.javaclassIndividual{publicIndividual(Stringname){this.name=name;}protectedIndividual(){}Stringname;}//第2层//Person.javaclassP
8、ersonextendsIndividual{publicPerson(Stringname)
此文档下载收益归作者所有