java中泛型的反射机制

/**
 * 2018.8.6
 * 作者:小孟鱼
 * 功能:java->反射机制
 * 
 */
package com.test;

import java.lang.reflect.Method;

public class Fanxin {
        public static void main(String[] args) {
        //泛型的写法    
        Gen<Bird> gen1=new Gen<Bird>(new 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>//T是我认为的一种类型但是我不知道是什么类型
{
    private T o;//o表示T传进来的类型
    //构造函数
    public Gen(T a){
        this.o=a;
    }
    //得到T的名称
    public void showTypeName() {
        System.out.println("类型是"+o.getClass().getName());
        //通过反射机制,我们可以得到T这个类型的很多信息(比如得到成员函数名)
        //将方法返回在一个数组中
        Method [] m=o.getClass().getDeclaredMethods();
        //打印一下
        for(int i=0;i<m.length;i++) 
        {
            System.out.println(m[i].getName());
        }
    }
    
    
}
 

猜你喜欢

转载自blog.csdn.net/weixin_42133768/article/details/81449023