一、Annotation入门
Annotation的入门比较简单,相关概念请看别人画的一幅导图,看不清的可以下载下来放大了看:
二、代码目标
以下代码实现的目标有两个:
1、将一个java bean的属性和属性值通过注解调用get方法放在一个map中。
2、将map中的数据通过注解调用set方法,设置到bean对象中。
三、代码实现
1、注解类
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 GetMethod {
public String value() ;
}
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 SetMethod {
public String value() ;
}
2、map和bean直接相互转化方法
public static Object Map2Bean(Map<String,Object> map,Object obj) throws Throwable{
if(obj == null)
return null;
Method[] methods = obj.getClass().getMethods();
for(Method method : methods){
if(method.isAnnotationPresent(SetMethod.class)){
SetMethod sm = method.getAnnotation(SetMethod.class);
String fieldName = sm.value();
Object fieldValue = map.get(fieldName);
method.invoke(obj, fieldValue);
}
}
return obj;
}
public static Map<String,Object> Bean2Map(Object bean,Map<String,Object> map) throws Throwable{
if(map == null)
map = new HashMap<String, Object>();
Method[] methods = bean.getClass().getMethods();
for(Method method : methods){
if(method.isAnnotationPresent(GetMethod.class)){
GetMethod gm = method.getAnnotation(GetMethod.class);
String fieldName = gm.value();
Object fieldValue = method.invoke(bean);
map.put(fieldName, fieldValue);
}
}
return map;
}
3、创建一个bean,并用注解标注
import java.util.List;
public class User {
private String name;
private int age;
private List<User> friends;
private boolean married;
@GetMethod("married")
public boolean isMarried() {
return married;
}
@SetMethod("married")
public void setMarried(boolean married) {
this.married = married;
}
@GetMethod("name")
public String getName() {
return name;
}
@SetMethod("name")
public void setName(String name) {
this.name = name;
}
@GetMethod("age")
public int getAge() {
return age;
}
@SetMethod("age")
public void setAge(int age) {
this.age = age;
}
@GetMethod("friends")
public List<User> getFriends() {
return friends;
}
@SetMethod("friends")
public void setFriends(List<User> friends) {
this.friends = friends;
}
}
4、测试
public static void main(String[] args) throws Throwable {
User user = new User();
user.setAge(18);
user.setMarried(true);
user.setName("UserName");
user.setFriends(new ArrayList<User>());
Map<String,Object> map = Bean2Map(user, null);
System.out.println(map.get("name"));
User u = (User) Map2Bean(map, new User());
System.out.println(u.getName());
}
结果:
UserName
UserName