java BeansUtil 反射原理实现2

来源:互联网 发布:淘宝论坛 买家 编辑:程序博客网 时间:2024/06/16 00:26

刚才写完了一个基于自定义的属性,挺灵活的,但是灵活的的付出几乎都是需要大部分代码的,写了之后感觉还不如用注解形式的比较简便于是花了几分钟写了一个基于注解的

class User{    @IgnoreProperty   //自定义的注解    private int id;    private String name;    private boolean demo;    int getId() {        return id;    }    void setId(int id) {        this.id = id;    }    String getName() {        return name;    }    void setName(String name) {        this.name = name;    }    boolean isDemo() {        return demo;    }    void setDemo(boolean demo) {        this.demo = demo;    }}
/** * Created with IntelliJ IDEA. * User: K * Date: 13-11-11 * Time: 下午3:24 * To change this template use File | Settings | File Templates. */   //用来说明这个类的描述范围 /*       ElementType取值                1.CONSTRUCTOR:用于描述构造器            2.FIELD:用于描述域            3.LOCAL_VARIABLE:用于描述局部变量            4.METHOD:用于描述方法            5.PACKAGE:用于描述包            6.PARAMETER:用于描述参数            7.TYPE:用于描述类、接口(包括注解类型) 或enum声明 */    /* RetentionPolicy取值    1.SOURCE:在源文件中有效(即源文件保留)    2.CLASS:在class文件中有效(即class保留)            3.RUNTIME:在运行时有效(即运行时保留) */@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME) //指定生命周期@Documentedpublic @interface IgnoreProperty {}


public class BeanUtils<T,K> {    public static void main(String args[])    {        BeanUtils<User,User> beanUtils = new BeanUtils<User,User>();        User user = new User();        User user1 = new User();        user.setId(1);        user.setDemo(false);        user.setName("w");        user1.setId(2);        user1.setDemo(true);        user1.setName("k");        System.out.println(user1.getId());        System.out.println(user1.getName());        System.out.println(user1.isDemo());        beanUtils.copyPropertiesAnnoations(user,user1);        System.out.println(user1.getId());        System.out.println(user1.getName());        System.out.println(user1.isDemo());    }    public void copyPropertiesAnnoations(T t,K k)    {        Class clazz = t.getClass();        Class target = k.getClass();        Field[] fields = clazz.getDeclaredFields();  //获取源类的所用字段        for (Field field : fields)    //遍历字段        {            Annotation annotations[] = field.getDeclaredAnnotations();//获取到这个字段上的注解            for (Annotation annotation : annotations)            {                String ann = "@com.ceit.cnivi.permission.util.bean.IgnoreProperty()";//这个包名是基于自己的注解的包名去写的 大家改成自己的就行了                if (ann.equals(annotation.toString()))                {                    return;                }            }            String fieldName = field.getName();  //获取名称            Field targetField  = null;            try {                targetField = target.getDeclaredField(fieldName);   //根据源类的属性获取目标类的属性            } catch (NoSuchFieldException e) {                continue;            }            if (field.getType()==targetField.getType())            {                String getMethodName = null;                String setMethodName = null;                if (field.getType().getName()=="boolean")                {                    getMethodName = "is"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);                    setMethodName  = "set" + fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);                } else                {                    getMethodName = "get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);                    setMethodName  = "set" + fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);                }                Method getMethod = null; //源类的get方法                Method setMethod = null;  //目标类的方法                try {                    getMethod = clazz.getDeclaredMethod(getMethodName);                    setMethod = target.getDeclaredMethod(setMethodName,field.getType());                    Object value = getMethod.invoke(t);   //通过get方法获得值                    setMethod.invoke(k,value);                } catch (NoSuchMethodException e) {                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.                } catch (InvocationTargetException e) {                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.                } catch (IllegalAccessException e) {                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.                }            }        }    }}


注意这个地方 得改成自己自定义注解所在的地方@com.ceit.cnivi.permission.util.bean.IgnoreProperty()


代码和之前的也没有什么太大的变化,只是加了一个注解的实现而已,但是感觉不是太好,基于注解那个采用的是字符串的比较,有比较好的方式的朋友,可以向我推荐一下,大家互相学习吧