码迷,mamicode.com
首页 > 编程语言 > 详细

java 泛型

时间:2016-10-11 20:52:55      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

泛型的存在,是为了使用不确定的类型。

为什么有泛型?

1. 为了提高安全

2. 提高代码的重用率

(自动 装箱,拆箱功能)

 

一切好处看代码:

package test1;

import java.lang.reflect.Method;

public class demo1 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Gen<Bird> gen1 = new Gen<Bird>(new Bird());
//        Gen<String> gen1 = new Gen<String>("Bird");
        gen1.showTypeName();
    }

}

//定义一个鸟类
class Bird 
{
    public void test1()
    {
        System.out.println("aa");
    }
    public void count(int  a,int  b)
    {
        System.out.println(a+b);
    }
}

//定义一个类
class Gen<T> {
    private T o;
    
    //构造函数
    public Gen(T a) 
    {
        o =a;
    }
    
    //得到T的类型名称
    public void showTypeName() 
    {
        System.out.println("类型是: "+o.getClass());
        //通过 反射机制,我们可以得到T这个类型的很多信息(比如得到成员函数名 )
        //o.getClass()后面有好多方法,getDeclareMethods获得他的方法,把他们存到一个数组里面
        //因为有好多方法 
        Method []m = o.getClass().getDeclaredMethods();
        //打印
        for(int i=0;i<m.length;i++)
        {
            System.out.println(m[i].getName());
        }
    }
    
}

 

java 泛型

标签:

原文地址:http://www.cnblogs.com/lt132024/p/5950394.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!