java解析注解的简单例子

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java解析注解的简单例子相关的知识,希望对你有一定的参考价值。

代码是根据慕课网的教程写的。

自定义类的注解:

package com.immoc.test;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Table {

    String value();
}

自定义方法的注解:

 1 package com.immoc.test;
 2 
 3 import java.lang.annotation.Documented;
 4 import java.lang.annotation.ElementType;
 5 import java.lang.annotation.Inherited;
 6 import java.lang.annotation.Retention;
 7 import java.lang.annotation.RetentionPolicy;
 8 import java.lang.annotation.Target;
 9 
10 @Target({ElementType.FIELD})
11 @Retention(RetentionPolicy.RUNTIME)
12 @Inherited
13 @Documented
14 public @interface Column {
15 
16     String value();
17 }

java类

package com.immoc.test;

@Table("user")
public class Filter {
    @Column("id")
    private int id;
    @Column("user_name")
    private String userName;
    @Column("nick_name")
    private String nickName;
    @Column("age")
    private int age;
    @Column("city")
    private String city;
    @Column("mail")
    private String mail;
    @Column("mobile")
    private String mobile;
    public String getMobile() {
        return mobile;
    }
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    public String getMail() {
        return mail;
    }
    public void setMail(String mail) {
        this.mail = mail;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getNickName() {
        return nickName;
    }
    public void setNickName(String nickName) {
        this.nickName = nickName;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    
}

测试类

package com.immoc.test;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Test {

    public static void main(String[] args) {
        Filter f1 = new Filter();
        f1.setId(10);
        
        Filter f2 = new Filter();
        f2.setUserName("tzzt01");
        f2.setAge(18);
        
        Filter f3 = new Filter();
        f3.setMail("[email protected],[email protected]");
        
        String sql1 = query(f1);
        String sql2 = query(f2);
        String sql3 = query(f3);
        
        System.out.println(sql1);
        System.out.println(sql2);
        System.out.println(sql3);
    }
    
    private static String query(Filter f) {
        StringBuilder sb = new StringBuilder();
        // 1.获取class
        Class c = f.getClass();
        // 2.获取table的名字
        boolean exists = c.isAnnotationPresent(Table.class);
        if (!exists) {
            return null;
        }
        Table t = (Table)c.getAnnotation(Table.class);
        String tableName = t.value();
        sb.append("select * from ").append(tableName).append(" where 1=1 ");
        // 3.遍历所有的字段
        Field[] fArray = c.getDeclaredFields();
        for(Field field :fArray) {
            // 4处理每个字段对应的sql
            // 4.1 拿到字段名
            boolean fExists = field.isAnnotationPresent(Column.class);
            if (!fExists){
                continue;
            }
            Column column = field.getAnnotation(Column.class);// 获得Column.class的注解
            String columnName = column.value();//获得字段名
            // 4.2拿到字段值
            String fieldName = field.getName();
            String getMethodName = "get" + fieldName.substring(0,1).toUpperCase()+fieldName.substring(1); // 获得getXXX
            Object fieldValue = null;
            try {
                Method getMethod = c.getMethod(getMethodName);
                fieldValue = getMethod.invoke(f);
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 4.3拼装sql
            if (fieldValue == null || (fieldValue instanceof Integer && (Integer)fieldValue == 0)) {
                continue;
            }
            sb.append(" and ").append(fieldName).append("=");
            
            if (fieldValue instanceof String) {
                if ( ( (String)fieldValue).contains(",") ) {
                    String[] values = ((String)fieldValue).split(",");
                    sb.append("in(");
                    for(String v : values) {
                        sb.append("‘").append(v).append("‘").append(",");
                    }
                    sb.deleteCharAt(sb.length()-1);
                    sb.append(")");
                } else {
                    sb.append("‘").append(fieldValue).append("‘");
                }
            } else if(fieldValue instanceof Integer) {
                sb.append(fieldValue);
            }
        }
        return sb.toString();
    }
}

以上是关于java解析注解的简单例子的主要内容,如果未能解决你的问题,请参考以下文章

JAVA自定义注解的使用的一个简单例子

java元注解,局部注解怎么解析

Java自定义注解

Java 注解自定义注解 ( 使用注解实现简单测试框架 )

@SerializedName注解

java注解是怎么实现的