泛型与反射机制

泛型
由于类型转换的错误,java虚拟机在编译时不会报错,而在运行时报异常。
所以安全隐患非常明显,为此我们需要泛型来弥补这一问题。

有了泛型,在集合类中添加对象时就不用再强转了。

import java.util.*;
public class main {

 
    public static void main(String[] args) {
        // TODO code application logic here
        //通过泛型将类型定下来
        ArrayList<snacks> ff=new ArrayList<snacks>();
        snacks ls1=new snacks("薯片",5f);
        ff.add(ls1);
        //泛型保证这里强制转换类型不出错,在申请集合类之前加上<snacks>
        snacks cls=(snacks)ff.get(0);
        
    }
    
}
class snacks
{
      private String Sname;
      private float Sprice;

    public snacks(String Sname, float Sprice) {
        this.Sname = Sname;
        this.Sprice = Sprice;
    }


}
class drink
{
        private String Dname;
       private float Dprice;
       private String Dcolor;
    public drink(String Dname, float Dprice, String Dcolor) {
        this.Dname = Dname;
        this.Dprice = Dprice;
        this.Dcolor = Dcolor;
    }
}


反射机制
是将 泛型 固定的类的所有方法和成员全部可以显示出来,
以供程序员可以确定程序的编写是否有误的机制。


import java.lang.reflect.Method;
import java.util.*;
public class main {

  
    public static void main(String[] args) {
        
       Bh <String> hw1 = new Bh<String>("货物1") ;
       hw1.lxmc();
       Bh <Integer> hw2 = new Bh<Integer>(123) ;
       hw2.lxmc();
       Bh <toy> hw3 = new Bh<toy>(new toy()) ;
       hw3.lxmc();
    }
}
class toy
{
   public void play()
   {
       System.out.println("They are playing games right now!");
   }
   public int calculte(int a,int b)
   {
     return a+b;
   }
}
//百货
class Bh<L>
{
       private L l;

     Bh(L l) 
     {
        this.l = l;
      }
//显示方法名称
    public void lxmc()
    {
        //去类型(class)名称(name)
        System.out.println("类型是"+l.getClass().getName());
        //用数组来接收类中方法的数量
        Method []a=l.getClass().getDeclaredMethods();
         for (int i=0;i<a.length;i++)
         {
             System.out.println("函数名为:" +a[i].getName());
         }
    }
       
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值