泛型

1.运行环境

jdk1.8.0_77 Intellij IDEA2018.3 x64

2.本章目标

基本的Annotation

自定义的Annotation

为注解添加属性

元注解

会提取注解信息

3.Annotation(注解) 概述

从 JDK 5.0 开始, Java 增加了对元数据(MetaData) 的支持, 也就是 Annotation(注解)

Annotation 其实就是代码里的特殊标记, 这些标记可以在编译, 类加载, 运行时被读取, 并执行相应的处理. 通过使用 Annotation, 程序员可以在不改变原有逻辑的情况下, 在源文件中嵌入一些补充信息.

Annotation 可以像修饰符一样被使用, 可用于修饰包,类, 构造器, 方法, 成员变量, 参数, 局部变量,的声明, 这些信息被保存在 Annotation 的 “name=value” 对中.

Annotation 能被用来为程序元素(类, 方法, 成员变量等) 设置元数据

4.基本的 Annotation

使用 Annotation 时要在其前面增加 @ 符号, 并把该 Annotation 当成一个修饰符使用. 用于修饰它支持的程序元素

三个基本的 Annotation:

@Override: 限定重写父类方法, 该注释只能用于方法

@Deprecated: 用于表示某个程序元素(类, 方法等)已过时

@SuppressWarnings: 抑制编译器警告.

5.代码展示

public class ClassMaxMin {
public static <W extends Comparable> Pair<W> getMaxAndMin(W [] ary){
W max = ary[0];
W min = ary[0];
for(W t:ary) {
if(max.compareTo(t)<0)
max = t;
if(min.compareTo(t)>0)
min = t;
}
return new Pair<W>(max, min);
}
}

=========================================================================

public class Pair <W>{
private W first;
private W second;

public W getFirst() {
return first;
}

public void setFirst(W first) {
this.first = first;
}

public W getSecond() {
return second;
}

public void setSecond(W second) {
this.second = second;
}

public Pair(W first, W second) {
super();
this.first = first;
this.second = second;
}

public Pair() {
super();
}

public void swap(){
W w = null;
w = first;
first = second;
second = w;
}

@Override
public String toString() {
return "Pair [first=" + first + ", second=" + second + "]";
}

//静态方法不能访问加注在类上的泛型
public static <W> void fun(W t){
System.out.println(t);
}


public static <E> void swapAry(E[] ary, int i, int j){
E temp = null;
temp = ary[i];
ary[i] = ary[j];
ary[j] = temp;
}
}

6.心得

当你把一件事当成自己生活中必不可少的时候,那么这件事你就用心对待了,就好比学习,如果你只是为了学习而学习,那么你只能说是学习好而不是爱学习。

 

原文地址:https://www.cnblogs.com/nanren/p/13585899.html