我们在静态方法中使用泛型的时候,我们需要在static 后面加上<T>泛型标识,下面是我给出的一个例子
package demo;
import java.util.Date;
/**
* created by yuyufeng on 2017/8/17.
*/
public class HelloService<T> {
void sayHello1(T t) {
System.out.println("hello: " + t);
}
/* static void sayHello2(T t) {
System.out.println("hello: " + t);
}
*/
static <T> void sayHello3(T t) {
System.out.println("hello: " + t);
}
public static void main(String[] args) {
HelloService<Date> helloService = new HelloService<>();
helloService.sayHello1(new Date());
HelloService.sayHello3(new Date());
}
}
/*
运行结果:
hello: Thu Aug 17 21:38:02 CST 2017
hello: Thu Aug 17 21:38:02 CST 2017
*/
如果不加,会报错。