自定义注解实现简单的orm映射框架

package com.mj;

import javax.xml.bind.Element;
import java.lang.annotation.*;
import java.lang.reflect.Field;

public class Test01 {

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface table{
        String value();
    }

    @Target(value = {ElementType.FIELD})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface myproper{
        public String name();
        public int length() default 0;

    }




    public static void main(String[] args) throws ClassNotFoundException {
        long l1 = System.currentTimeMillis();
        Class<?> aClass = Class.forName("com.mj.Student");
        myproper declaredAnnotation2 = aClass.getDeclaredAnnotation(myproper.class);
        StringBuffer sb=new StringBuffer();
        sb.append("select ");
        Field[] declaredFields = aClass.getDeclaredFields();
        for (int i=0;i<declaredFields.length;i++){
            Field declaredField = declaredFields[i];
            myproper declaredAnnotation = declaredField.getDeclaredAnnotation(myproper.class);
            String name = declaredAnnotation.name();
            sb.append(name);
            if(i<declaredFields.length-1){
                sb.append(",");
            }
        }

        table declaredAnnotation1 = aClass.getDeclaredAnnotation(table.class);
        String tablename = declaredAnnotation1.value();
        sb.append(" from ").append(tablename);
        long l2 = System.currentTimeMillis();
//        System.out.println((l2-l1));
        System.out.println(sb.toString());

    }
}
package com.mj;

@Test01.table("student")
class Student {
    @Test01.myproper(name="name",length = 255)
    private String s_name;
    @Test01.myproper(name="age",length = 11)
    private int s_age;
    @Test01.myproper(name="id",length = 11)
    private int s_id;
}

猜你喜欢

转载自www.cnblogs.com/a1304908180/p/11376206.html