推荐一下一个有趣的表情包收集网站,也可以在线制作表情包,欢迎访问:撸表情
在上一篇Jave中的Annotation详解中对Java Annotation作了一个详细的介绍,但是没有例子,不够直观,所以就有了这篇——一个例子:
一、ClassAnnotation修饰类
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ClassAnnotation
{
String value();
}
二、MethodAnnotation修饰方法
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MethodAnnotation
{
String methodName();
String methodDestination();
}
三、FieldAnnotation修饰属性
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FieldAnnotation
{
String value();
}
四、AnnotationClass源码
@ClassAnnotation("Annotation用于类")
public class AnnotationClass
{
@MethodAnnotation(methodName="method1",methodDestination="Annotation用于方法")
public String method1()
{
return this.id;
}
@MethodAnnotation(methodName="method2",methodDestination="Annotation用于方法")
public String method2()
{
return null;
}
@FieldAnnotation("Annotation用于属性")
public String id="123456";
}
五、AnnotationTest测试
import java.lang.reflect.Method;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;
public class AnnotationTest {
public static void main (String[] args) throws ClassNotFoundException
{
String className="AnnotationClass";
Class test=Class.forName(className);
//判断是否采用ClassAnnotation
boolean flag=test.isAnnotationPresent(ClassAnnotation.class);
if(flag)
{
ClassAnnotation classAnnotation=(ClassAnnotation)test.getAnnotation(ClassAnnotation.class);
System.out.println("类描述:"+classAnnotation.value());
}
Set<Method> set=new HashSet<Method>();
Method[] methods=test.getMethods();
for(int i=0;i<methods.length;i++)
{
//判断是否采用MethodAnnotation
if(methods[i].isAnnotationPresent(MethodAnnotation.class))
set.add(methods[i]);
}
for(Method m:set)
{
MethodAnnotation methodAnnotation=m.getAnnotation(MethodAnnotation.class);
System.out.println("方法:"+methodAnnotation.methodName()+" 目的:"+methodAnnotation.methodDestination());
}
Set<Field> set2=new HashSet<Field>();
Field[] fields=test.getFields();
for(int i=0;i<fields.length;i++)
{
//判断是否采用FieldAnnotation
if(fields[i].isAnnotationPresent(FieldAnnotation.class))
set2.add(fields[i]);
}
for(Field f:set2)
{
FieldAnnotation fieldAnnotation=f.getAnnotation(FieldAnnotation.class);
System.out.println("属性的描述:"+fieldAnnotation.value());
}
}
}
单独保存成java文件,编译下就可以运行了,结果比较简单就不截图了,源码都在上面,这个是以前自己学的时候写的书上的代码,相差不大,快1年了把,时间过得好快!欢迎交流!