泛型

泛型类

在类名后面添加<T> -> 占位符 代表实际使用的类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class GenericClass {
public static void main(String[] args) {
Box<String> stringBox = new Box<>();
stringBox.setT("Here is StringBox");
System.out.println(stringBox.getT());

Box<Integer> integerBox = new Box<>();
integerBox.setT(123);
System.out.println(integerBox.getT());
}
}
class Box<T> {
private T t;

public T getT() {
return t;
}

public void setT(T t) {
this.t = t;
}
}

Here is StringBox
123

泛型方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class GenericMethod {
public static <T> void PrintArray(T[] array) {
for (T element : array) {
System.out.println(element);
}
}
public static void main(String[] args) {
//创建不同数组类型
Integer[] intArray = {1,2,3};
Double[] doubleArray = {1.1,2.2,3.3};
String[] stringArray = {"H","e","l","l","o"};
PrintArray(intArray);
PrintArray(doubleArray);
PrintArray(stringArray);
}
}


注解

元注解

定义自定义注解的注解

@Retention:自定义注解保留到以下哪个阶段
JAVA运行主要周期:源文件->编译成.class文件->运行时
RUNTIME:如果要通过反射获取注解信息,则需要使用RUNTIME
@Retention(RetentionPolicy.RUNTIME)

@Target: 用于描述注解的使用范围,限制注解解释的类型
@Target(ElementType.ANNOTATION_TYPE)
具体value取值可以去现查一波

Documented:表示是否将注解生成在JAVAdoc中
@Inherited:表示是否允许子类继承父类的注解

标准注解

@Override
@Deprecated:表示被注解的代码已经过时,不建议使用
@SuppressWarnings:表示忽略警告 ->不输出对应的编译警告