1、AnnotationDemo
package class7.annotation;
import java.util.Date;
//@SuppressWarnings("all")
public class AnnotationDemo {
private int num;
@Override
public String toString() {
return "AnnotationDemo{" +
"num=" + num +
'}';
}
/**
* 计算两个整数相加的和
*
* @param num1 第一个数
* @param num2 第二个数
* @return
* 两个数相加的和
*/
public int add(int num1,int num2){
return num1+num2;
}
@Deprecated
public void test(){
System.out.println("test");
}
public static void main(String[] args) {
AnnotationDemo ad = new AnnotationDemo();
// ad.test();
//使用反射技术创建对象
try {
AnnotationDemo ad2 = (AnnotationDemo)Class.forName("class7.annotation.AnnotationDemo").newInstance();
ad2.test();
} catch (Exception e) {
e.printStackTrace();
}
Date date = new Date();
System.out.println(date.getYear());
}
}
2、FunctionInterfaceDemo
package class7.annotation;
@FunctionalInterface
public interface FunctionInterfaceDemo {
// void add(int a,int b);
void sub(int a, int b);
}
3、MetaAnnotation
package class7.annotation;
import java.lang.annotation.*;
@MyAnnotation(age = 20,joys = {"a","b","c"})
public class MetaAnnotation {
public void print(){
System.out.println("print... ...");
}
}
//自定义注解
//target是说明自定义注解在什么位置可以使用,包、类、方法、属性等等
@Target({ElementType.METHOD,ElementType.TYPE})
//retention说明当前注解可以适用的环境,或者说什么级别保存注释信息,有三个级别,源码级别SOURCE、类级别CLASS,运行时环境RUNTIME,默认一般是RUNTIME级别
@Retention(RetentionPolicy.RUNTIME)
//说明注解是否可以显示在javadoc中
@Documented
//说明当前注解是否能被继承
@Inherited
@interface MyAnnotation{
//定义的方式看起来像是方法,但是实际上在使用注解的时候需要配置的一些参数名称和类型,默认的名称是value
//自定义注解的中填写的参数名称对应方法名,参数的类型对应方法的返回类型,需要一个一个的添加,写起来很麻烦,因此一般给它一些默认值。
int id() default 1;
String name() default "";
int age() default 18;
String[] joys() default "";
}
4、Test1
package class7.annotation;
public class Test1 {
public void test(){
System.out.println("test");
}
}