自定义注解和最常用的基本设计模式

1.自定义注解

2.手写自定义注解模拟ORM框架映射

package com.json.ioc;


import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Field;

@Retention(RetentionPolicy.RUNTIME)
@interface SetTable {

    String value();


}

@Retention(RetentionPolicy.RUNTIME)
@interface Setproperty {
    String value();
    int length();
}



public class TestMain{
    public static void main(String[] args) throws Exception {
        Class<?> aClass = Class.forName("com.json.ioc.User");
        //获取该类的所有注解,不能获取方法上的
//             Annotation[] declaredAnnotations = aClass.getDeclaredAnnotations();
//        for (Annotation annotation : declaredAnnotations){
//            System.out.println(annotation.toString());
//        }
        //得到所有的属性,获取他们的上面的注解
        Field[] declaredFields = aClass.getDeclaredFields();
        StringBuffer buf = new StringBuffer();
        buf.append("select ");
        for (int i = 0; i <declaredFields.length ; i++) {
            Setproperty setproperty = declaredFields[i].getAnnotation(Setproperty.class);
            String value = setproperty.value();
            int length = setproperty.length();
            buf.append(value);

            if(i==(declaredFields.length-1)){
                buf.append("  from  ");
            } else {
                buf.append(" ,");
            }
        }
        SetTable annotation = aClass.getAnnotation(SetTable.class);
        //获取表的名称这个value就是自己定义的那个属性
        String value = annotation.value();
        buf.append(value);
        System.out.println(buf);
    }
}

猜你喜欢

转载自www.cnblogs.com/itcastwzp/p/10972975.html