Java自定义注解入门举例

转载请注明出处:http://blog.csdn.net/Hello_Chillax/article/details/48805387

学Android也有一年多了,打算分出一半的精力来学习JavaWeb的开发。
JavaWeb中第一个接触的框架就是SpringMVC了,其中用到了“注解”这个东西。作为入门,自己写了个例子,记录一下。

我们打算写一个quary(Filter filter) 函数来根据model生成一个SQL语句。

首先,Filter.java

/**
 * Created by Xiao on 2015/9/29.
 */
@Table("User")
public class Filter {

    @Column("name")
    private String name;

    @Column("pwd")
    private String pwd;

    @Column("age")
    private String age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

接下来,Table.java && Column.java

/**
 * Created by Xiao on 2015/9/29.
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Table {
    String value();
}

/**
* Created by Xiao on 2015/9/29.
*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Column {
String value();
}

最后,测试类 Test.java

/**
 * Created by Xiao on 2015/9/29.
 */
public class Test {
    public static void main(String[] args) {
        Filter filter = new Filter();
        filter.setName("肖哥");
        filter.setAge("23");
        System.out.println(quary(filter));
    }

    public static String quary(Filter filter) {
        StringBuilder sb = new StringBuilder();
        Class c = filter.getClass();
        if (!c.isAnnotationPresent(Table.class)) {
            return null;
        }
        sb.append("select * from " + ((Table) c.getAnnotation(Table.class)).value()).append(" where ");
        for (Field field : c.getDeclaredFields()) {
            Column column = field.getDeclaredAnnotation(Column.class);
            field.setAccessible(true);
            try {
                Object value = field.get(filter);
                if (value == null || (value.getClass() == Integer.class && (Integer) value == 0)) continue;
                sb.append(column.value()).append("=").append(field.get(filter)).append(" and ");
            } catch (Exception e) {
                e.printStackTrace();
            }
            field.setAccessible(false);
        }
        sb.replace(sb.lastIndexOf(" and "),sb.length(),"");
        return sb.toString();
    }
}

输出结果:

select * from User where name=肖哥 and age=23

完成。

总结:这个小例子说明了如何自定义注解。以及提供了一个应用场景。
其中涉及到了Reflect的知识,还算比较有参考价值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值