package com.self;
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;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import com.self.A.type;
import com.self.Yts.YtsType;
@A(classType=type.service)
@B(getName="helo")
public class AnnoTest {
@B(getName="新名字")
public void sayHello(String name)
{
System.out.println(name+" the world");
}
public static void main(String[] args) throws Exception {
ParseAnno anno = new ParseAnno();
anno.parseMethod(AnnoTest.class);
anno.parseClass(AnnoTest.class);
}
}
@Documented
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface A
{
public enum type{util,dao,service}
public type classType() default type.util;
}
@Documented
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@interface B
{
public String getName() default "";
}
class ParseAnno
{
public void parseClass(Class clazz)
{
Object temp = (A)clazz.getAnnotation(A.class);
if(temp!=null && temp instanceof A)
{
A a = (A)clazz.getAnnotation(A.class);
System.out.println(a.classType().equals(A.type.util));
}
if(temp!=null && temp instanceof B)
{
B b = (B) temp;
System.out.println(b.getName());
}
}
public void parseMethod(Class clazz) throws Exception
{
Object obj = clazz.getConstructor(new Class[]{}).newInstance(new Object[]{});
for(Method method: clazz.getDeclaredMethods())
{
B b = method.getAnnotation(B.class);
if(b!=null)
{
try {
method.invoke(obj, b.getName());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
例子全程手写,如果想看详细解释,请看其他网站资料,可以直接运行