java基础 泛型

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

为什么有泛型?

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());
        }
    }
    
}
原文地址:https://www.cnblogs.com/lt132024/p/5950394.html