注解,泛型,反射是java框架的基石。如见常见的框架中如EventBus,SpringMVC等,我们都不难发现里面有很多注解。所以,学习注解是非常有必要的。废话不多说,这里的小Demo可以复习下注解,是怎么自定义,并且是如何解析的。
这里不会看到注解的基本定义,这样的定义与元注解的使用方法网友已经给我们提供很多很好的文章。这里我贴上注解使用的Demo:
- 工程结构:
-
- Myanno为注解
- Person为实体类
- Myanno定义
package com.anno.test;
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;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Myanno {
String name();
int age();
String addr();
}
- Person实体
package com.anno.test;
public class Person {
private String name;
private int age;
private String addr;
public Person() {
// TODO Auto-generated constructor stub
}
@Myanno(addr = "name", age = 20, name = "刘婵")
public void setPerson(String name,int age,String addr){
this.name = name;
this.age =age;
this.addr = addr;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", addr=" + addr + "]";
}
}
- 注解解析
package com.anno.test;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
public class MainActivity {
public static final String PATHANNO = "com.anno.test.Person";
public static final String PATHANNOMETHED = "com.anno.test.Person.setPerson()";
public static void main(String args[]) throws Exception {
Class clazz = Class.forName(PATHANNO);
Person newInstance = (Person) clazz.newInstance();
Method[] methods = clazz.getMethods();
System.out.println(Arrays.toString(methods));
for(Method method:methods){
boolean annotationPresent = method.isAnnotationPresent(Myanno.class);
if(annotationPresent){
Myanno annotation = method.getAnnotation(Myanno.class);
System.out.println(annotation.addr()+"\n");
System.out.println(annotation.name()+"\n");
System.out.println(annotation.age()+"");
//obj为实际调用方法的对象,args为函数实参
method.invoke(newInstance,new Object[]{annotation.name(),annotation.age(),annotation.addr()});
System.out.println(newInstance.toString());
}
}
}
}