java注解技术(Annotation)(二)

2014-11-24 02:55:47 · 作者: · 浏览: 4
ge = age; } }


package cn.edu.chd.annotation2;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface InjectPerson
{
    String name();
    int age();
}

package cn.edu.chd.annotation2;
public class PersonDao
{
    private Person person;
    public Person getPerson()
    {
        return person;
    }
    @InjectPerson(name="hehe",age=12)
    public void setPerson(Person person)
    {
        this.person = person;
    }
}

package cn.edu.chd.annotation2;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Demo
{
    public static void main(String[] args) throws Exception
    {
//        1.得到要注入的属性
        PropertyDescriptor pd = new PropertyDescriptor("person", PersonDao.class);
//        2.得到要注入的属性需要的类型
        Class clazz = pd.getPropertyType();
//        3.创建属性需要的对象
        Object p = clazz.newInstance();
//        4.得到属性的写方法
        Method setPerson = pd.getWriteMethod();
//        5.反射出方法上声明的注解
        InjectPerson inject = setPerson.getAnnotation(InjectPerson.class);
//        6.得到注解上声明的信息,填充person对象
        Method[] methods = inject.getClass().getMethods();
        for(Method m : methods)
        {
            String methodName = m.getName();
            try
            {
                Field f = Person.class.getDeclaredField(methodName);
                Object value = m.invoke(inject,null);
                f.setAccessible(true);
                f.set(p, value);
            } catch (Exception e)
            {
                continue;
            }
        }
         
//        7.把填充了数据的person通过setPerson方法整到personDao对象上
        PersonDao dao = new PersonDao();
        setPerson.invoke(dao,p);
        System.out.println(dao.getPerson().getName());
    }
}

控制台输出:hehe