常用的注解及分类

三个内置注解:*
package annotation;
import java.util.ArrayList;
import com.sun.xml.internal.bind.v2.schemagen.xmlschema.List;
public class 三个内置注解 extends Object{
//三个内置注解
@Override//重写
public String toString() {
return super.toString();
}
@Deprecated//不推荐使用,被淘汰,存在更好的方法
private static void test1() {
System.out.println("@Deprecated");
}
@SuppressWarnings(value = { “all” })//镇压警告
public void test02() {
List list= (List) new ArrayList();
}
public static void main(String[] args) {
test1();
}
}

元注解:
package annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//测试元注解
@MyAnnotation
public class 元注解 {
@MyAnnotation
public void test() {
}
}
//定义一个注解 target表示注解可以用在哪些地方
@Target(value = {ElementType.METHOD,ElementType.TYPE,ElementType.TYPE_PARAMETER})
@Retention(value=RetentionPolicy.RUNTIME)//表示注解什么时间有效,source<class<runtime
@Documented//表示是否将注解是否生成在javadoc中
@Inherited //子类可以继承父类的注解
@interface MyAnnotation{
}

自定义注解:
package annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

//测试元注解
@MyAnnotation
public class 自定义注解 {
//注解可以显示
@MyAnnotation2(name=“liul”,age=18,schools=“小学”)
public void test() {
}
@MyAnnotation3(“liul”)
public void test3() {
}
}
//定义一个注解 target表示注解可以用在哪些地方
@Target(value = {ElementType.METHOD,ElementType.TYPE,ElementType.TYPE_PARAMETER})
@Retention(value=RetentionPolicy.RUNTIME)//表示注解什么时间有效,source<class<runtime
@Documented//表示是否将注解是否生成在javadoc中
@Inherited //子类可以继承父类的注解
@interface MyAnnotation2{
//注解的参数:参数类型+参数名();
String name();
int age() default 0 ;
int id() default -1;//如果默认值为-1,表示不存在;indexof,如果找不到,返回-1;
String[] schools();
}
//只有一个参数用value可以
@interface MyAnnotation3{
String value();
}

猜你喜欢

转载自blog.csdn.net/l_iulei/article/details/106911742
今日推荐