非泛型类中的泛型方法

import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import javax.swing.event.ListSelectionEvent;

/*
* 非泛型类中定义泛型方法
* T…表示可变参数,实质为数组(T[])
*/
public class Test {

//泛型方法
 public static <T> void Method(T t){
     System.out.println(t);
 }

 //释放资源,一般用于文件流中
 //此时T继承Closeable
 public static <T extends Closeable> void ListSelectionEvent(T... a) {
    for(T temp:a) {
        if(temp!=null) {
            try {
                temp.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
 }    

//流文件一般会存在异常
public static void main(String[] args) throws FileNotFoundException {
Method(“it’s good”);
ListSelectionEvent(new FileInputStream(“a.txt”));
}

}

猜你喜欢

转载自blog.csdn.net/zhang1996922/article/details/79312999