import java.lang.annotation.*;
/**
* Created by jinzhao.w on 2015/5/14.
*/
@Retention(RetentionPolicy.RUNTIME)
//@Target({ElementType.TYPE,ElementType.METHOD})
@Target(ElementType.METHOD)
@Documented
public @interface MyAnnotation {
//定义一个枚举
public enum PersonType{MAN,WOMAN,OLD,YOUNG};
//定义一个注解参数
public PersonType type() default PersonType.MAN;
public String name() default "";
public int age();
public String[] clothColor() default {"red","black"};
}
---------------------------------------------------------------------------------------------
import java.io.Serializable;
/**
* Created by 737597978 on 2015/5/14.
*/
public class Student implements Serializable {
@MyAnnotation(type = MyAnnotation.PersonType.MAN, name = "wangjinzhao", age = 28, clothColor = {"green", "blue"})
public String setValue(MyAnnotation.PersonType stuType, String name, int age, String[] clothColor) {
StringBuffer buffer = new StringBuffer();
for(String color:clothColor){
buffer.append(color+"");
}
System.out.println("成功调用了方法并注入了参数:[" + stuType + "," + age + "," + name+"," + buffer.toString()+ "} ]");
return stuType + "," + age + "," + name+"," + buffer.toString();
}
public void print(){
System.out.println("=================");
}
}
-------------------------------------------------------------------------------------
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Created by 737597978 on 2015/5/14.
*/
public class AnnotationParseTest {
public String parseMyAnnotationMethod(Class<?> clazz) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
//通过反射的方式创建对象
Object obj=Class.forName("com.wangjz.annotation.Student").newInstance();
Student stu=(Student)obj;
stu.print();
//通过反射方式创建对象
Object anotherObject=clazz.getConstructor(new Class[]{}).newInstance(new Object[]{});
for(Method method:clazz.getDeclaredMethods()){
MyAnnotation annotation=method.getAnnotation(MyAnnotation.class);
if(annotation!=null){
MyAnnotation.PersonType type=annotation.type();
String name=annotation.name();
int age=annotation.age();
String [] colors=annotation.clothColor();
return (String)method.invoke(obj,type,name,age,colors);
}
}
return "";
}
public static void main(String[] args) throws Exception{
AnnotationParseTest parse = new AnnotationParseTest();
String returnValue = parse.parseMyAnnotationMethod(Student.class);
System.out.println(returnValue);
}
}