JAVA之泛型

/**
 * 泛型讲解
 */
package com.test;

import java.lang.reflect.Method;

import java.util.ArrayList;

public class test9 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        //案例一
        ArrayList<Pig> al = new ArrayList<Pig>();
        Pig pig1 = new Pig();
        al.add(pig1);
        Pig temp = al.get(0); //如果不用泛型则是这样:Pig temp = (Pig)al.get(0);
        temp.showMessage1();
        //案例二
        Bird bd = new Bird();
        Gen<Bird> gen1 = new Gen<Bird>(bd);
        gen1.showTypeName();
        gen1.showMessage2();
    }

}

//案例一

class Pig
{
    private String name;
    private int age;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    public void showMessage1()
    {
        System.out.println("这是第一个案例!!");
    }
    
}

//案例二

//定义一个泛型类
class Gen<T> //T是参数类型
{
    private T o;
    
    //构造函数
    public Gen(T a)
    {
        o = a;
    }
    
    //得到T的类型名称
    public void showTypeName()
    {
        System.out.println("类型是:"+o.getClass().getName());
        //通过JAVA反射机制,我们可以得到T这个类型的相关信息
        Method[] m = o.getClass().getDeclaredMethods();
    }
    
    public void showMessage2()
    {
        System.out.println("这是案例二!!");
    }
}


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

原文地址:https://www.cnblogs.com/milantgh/p/4040287.html