Skip to content

Commit 4f4808b

Browse files
author
chenweijie
committed
泛型方法和泛型类
1 parent a34cf58 commit 4f4808b

File tree

3 files changed

+118
-0
lines changed

3 files changed

+118
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.chen.api.util.generic.GenericClass;
2+
3+
/**
4+
* 泛型类,是在实例化类的时候指明泛型的具体类型;
5+
* <p>
6+
* 泛型方法,是在调用方法的时候指明泛型的具体类型。
7+
*
8+
* @author Chen WeiJie
9+
* @date 2019-12-04 17:12:50
10+
**/
11+
public class Generic<T> {
12+
13+
14+
private T key;
15+
16+
17+
public Generic(T key) {
18+
this.key = key;
19+
}
20+
21+
22+
public T getKey() {
23+
return key;
24+
}
25+
26+
public void setKey(T key) {
27+
this.key = key;
28+
}
29+
30+
31+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.chen.api.util.generic.GenericClass;
2+
3+
/**
4+
* @author Chen WeiJie
5+
* @date 2019-12-04 17:15:47
6+
**/
7+
public class GenericTest {
8+
9+
10+
public static void main(String[] args) {
11+
12+
//在实例化泛型类时,必须指定T的具体类型
13+
Generic<Integer> generic = new Generic<>(123);
14+
Generic<String> genericStr = new Generic<>("221");
15+
System.out.println("泛型测试 key is " + generic.getKey());
16+
System.out.println("泛型测试 key is " + genericStr.getKey());
17+
18+
}
19+
20+
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package com.chen.api.util.generic.genericMethod;
2+
3+
/**
4+
* 泛型方法,是在调用方法的时候指明泛型的具体类型。
5+
* <p>
6+
* public 与 返回值中间<T>非常重要,可以理解为声明此方法为泛型方法。
7+
*
8+
* @author Chen WeiJie
9+
* @date 2019-12-05 15:37:05
10+
**/
11+
public class GenericMethod {
12+
13+
14+
/**
15+
* 1)public 与 返回值中间<T>非常重要,可以理解为声明此方法为泛型方法。
16+
* 2)只有声明了<T>的方法才是泛型方法,泛型类中的使用了泛型的成员方法并不是泛型方法。
17+
* 3)<T>表明该方法将使用泛型类型T,此时才可以在方法中使用泛型类型T。
18+
* 4)与泛型类的定义一样,此处T可以随便写为任意标识,常见的如T、E、K、V等形式的参数常用于表示泛型。
19+
*
20+
* @param tClass
21+
* @param <T>
22+
* @return
23+
* @throws IllegalAccessException
24+
* @throws InstantiationException
25+
*/
26+
public static <T> T getGenericMethod(Class<T> tClass) throws IllegalAccessException, InstantiationException {
27+
28+
T instance = tClass.newInstance();
29+
return instance;
30+
}
31+
32+
33+
public <E> void getClassType(E e) {
34+
System.out.println(e);
35+
}
36+
37+
38+
/**
39+
* 泛型方法与可变参数
40+
*
41+
* @param args
42+
* @param <T>
43+
*/
44+
public <T> void printMsg(T... args) {
45+
46+
for (T arg : args) {
47+
System.out.println(arg.toString());
48+
}
49+
}
50+
51+
52+
//泛型类中的’?’是类型实参,而不是类型形参
53+
54+
55+
public static void main(String[] args) {
56+
57+
GenericMethod genericMethod = new GenericMethod();
58+
//普通泛型方法
59+
String name = "zhang san";
60+
genericMethod.getClassType(name);
61+
62+
// 可变参数的泛型方法
63+
genericMethod.printMsg("111", 222, "aaaa", "2323.4", 55.55);
64+
}
65+
66+
67+
}

0 commit comments

Comments
 (0)