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的知识,还算比较有参考价值。

你可能感兴趣的:(Java自定义注解入门举例)