java注解:
@SuperressWarning("all")取消警告
@Deprecated(过时)
String name() ;
可以使基本类型和基本类型的一维数组
@MyAnnotation(value="");或者@MyAnnotation(value="")
3.4.2String[] value()
@MyAnnotation(value={"a","bv"});
@MyAnnotation({"a","b"})
@MyAnnotation(("a"))
@MyAnnotation("a")
RetentionPolicy.SOURCE:注解存在于源文件中
RetentionPolicy.CLASS:注解存在于源字节码文件中
RetentionPolicy.RUNTIME:注解存在于运行时
@Target:注解出现的位置
type,method,...
5.2
@Documented: 用于指定被该元 Annotation 修饰的 Annotation 类将被 javadoc 工具提取成文档.
@Inherited: 被它修饰的 Annotation 将具有继承性.如果某个类使用了被 @Inherited 修饰的 Annotation, 则其子类将自动具有该注解
@Retention(RetentionPolicy.RUNTIME)
//@Retention(RetentionPolicy.CLASS)
@Target(ElementType.METHOD)
package com.luo.annotation
public @interface MyTest {
}
public class Test1 {
@MyTest
public void test1(){
System.out.println("test1执行了");
}
}
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//反射注解:
//取得字节码
//反射其中方法成员
//看谁的上面有MyTest
//谁有就执行谁
public class MyJunitRunner {
public static void main(String[] args) throws Exception, IllegalArgumentException, InvocationTargetException, InstantiationException {
Class clazz = Test1.class;
Method[] methods = clazz.getMethods();
for(Method m:methods){
if(m.isAnnotationPresent(MyTest.class)){
m.invoke(clazz.newInstance(), null);//执行方法
}
}
}
}
1.作用:
替代配置文件2.常用三个:
@Override@SuperressWarning("all")取消警告
@Deprecated(过时)
3.自定义注解:
3.1注解本身:
public @interface MyAnnotation()3.2注解属性:
基本形式:类型 属性名称()String name() ;
可以使基本类型和基本类型的一维数组
3.3定义默认值:
String name() default "";3.4定义属性:
3.4.1String value()@MyAnnotation(value="");或者@MyAnnotation(value="")
3.4.2String[] value()
@MyAnnotation(value={"a","bv"});
@MyAnnotation({"a","b"})
@MyAnnotation(("a"))
@MyAnnotation("a")
5.元注解:
5.1定义:服务于注解的注解就是元注解。
@Retention:注解的保留范围RetentionPolicy.SOURCE:注解存在于源文件中
RetentionPolicy.CLASS:注解存在于源字节码文件中
RetentionPolicy.RUNTIME:注解存在于运行时
@Target:注解出现的位置
type,method,...
5.2
@Documented: 用于指定被该元 Annotation 修饰的 Annotation 类将被 javadoc 工具提取成文档.
@Inherited: 被它修饰的 Annotation 将具有继承性.如果某个类使用了被 @Inherited 修饰的 Annotation, 则其子类将自动具有该注解
5.3模拟Junit(步骤如下:)
5.3.1定义注解:
//要添加元注解;@Retention(RetentionPolicy.RUNTIME)
//@Retention(RetentionPolicy.CLASS)
@Target(ElementType.METHOD)
package com.luo.annotation
public @interface MyTest {
}
5.3.2s使用注解
package com.luo.annotation;public class Test1 {
@MyTest
public void test1(){
System.out.println("test1执行了");
}
}
5.3.3构造注解:
package com.luo.annotation;import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//反射注解:
//取得字节码
//反射其中方法成员
//看谁的上面有MyTest
//谁有就执行谁
public class MyJunitRunner {
public static void main(String[] args) throws Exception, IllegalArgumentException, InvocationTargetException, InstantiationException {
Class clazz = Test1.class;
Method[] methods = clazz.getMethods();
for(Method m:methods){
if(m.isAnnotationPresent(MyTest.class)){
m.invoke(clazz.newInstance(), null);//执行方法
}
}
}
}