标签:
为什么要学习注解,学习注解有什么好处,学完能做什么?
1,能够读懂别人写的代码,特别是框架中的相关的代码。
2,让编程更加简洁,代码更加清晰
概念自己百度
java中常见的注解
~常见注解(JDK注解)
package 注解; public interface Person { public String name(); public int age(); @Deprecated//表示这个类中的方法已经过时了 public void sing(); } package 注解; public class Child implements Person{ @Override public String name() { // TODO Auto-generated method stub return null; } @Override public int age() { // TODO Auto-generated method stub return 0; } @Override public void sing() { // TODO Auto-generated method stub } } package 注解; public class MainTest { @SuppressWarnings("deprecation") public void sing(){ Person p = new Child(); //虽然这个方法过时了,但是我要用这个方法,我就要添加注解 p.sing(); } public static void main(String[] args) { } }
常见的第三方注解
~Spring中的注解{@Autowired,@Service,@Repository};MyBatis中的注解{@InsertProvider,@UpdateProvider,@Options};
public class UserMangerImpl implements UserManger{ private UserDao userDao; public void setUserDao(UserDao userDao){ this.userDao = userDao; } } 用XML文件配置 //配置文件 <bean id="userMangerImpl" class="com.ss.spring.annotion.service.UserMangerImpl"> <property name="userDao" ref="userDao"/> </bean> <bean id="userDao" class="com.ss.spring.annotion.persistence.UserMangerDaoImpl"> <property name="sessionFactory" ref="mySessionFactory"/> </bean> //注解 引入Autowired public class UserMangerImpl implements UserManger{ @Autowired private UserDao userDao; }
~注解分类
源码注解
编译注解
运行注解
~自定义注解
语法:
@Target({ElementType.METHOD,ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME)//生命周期 @Inherited//允许子类继承 @Documented//生成javadoc带有注解信息 public @interface Description{ String desc();//成员无参无异常的声明方式 String author() int age() default 18;//可以用default为成员指定一个默认值 }
定义注解的时候,成员类型是受限制的,合法的类型有原始类型及String,Class,Annotation,Enumeration.
如果注解只有一个成员,成员的名称必须取名是value(),在使用的时候可以忽略成员名和复制号(=)
使用注解的语法:
@<注解名>(<成员名1>=<成员值1>,<成员名2>=<成员值2>)
比如:@Description(desc="i am tom",author="boy",age=18)
public String eyeColor(){
return "red";
}
~解析注解
package 注解; import java.lang.annotation.Annotation; import java.lang.reflect.Method; public class Parse { public static void main(String[] args) { //1使用类加载器加载类 try { Class c = Class.forName("注解.Child"); //2找到类上面的注解 boolean isExit = c.isAnnotationPresent(Description.class); if (isExit) { //3拿到注解实例 Description description =(Description)c.getAnnotation(Description.class); System.out.println(description); } //找到方法上的注解 Method[] ms = c.getMethods(); for (Method m:ms) { boolean isMethodExit = m.isAnnotationPresent(Description.class); if (isMethodExit) { //3拿到注解实例 Description description =(Description)m.getAnnotation(Description.class); System.out.println(description); } } //另一种解析方法 for (Method m:ms) { Annotation[] as = m.getAnnotations(); for (Annotation a:as) { if (a instanceof Description) { Description description =(Description)a; System.out.println(description.value()); } } } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
继承的测试
package 注解; @Description("i am interfacer") public class Person { @Description("i am interface method") public String name(){ return null; } public int age(){ return 0; } @Deprecated//表示这个类中的方法已经过时了 public void sing(){ } } package 注解; public class Child extends Person{ public String name() { // TODO Auto-generated method stub return null; } @Override public int age() { // TODO Auto-generated method stub return 0; } @Override public void sing() { // TODO Auto-generated method stub } } package 注解; import java.lang.annotation.Annotation; import java.lang.reflect.Method; public class Parse { public static void main(String[] args) { //1使用类加载器加载类 try { Class c = Class.forName("注解.Child"); //2找到类上面的注解 boolean isExit = c.isAnnotationPresent(Description.class); if (isExit) { //3拿到注解实例 Description description =(Description)c.getAnnotation(Description.class); System.out.println(description); } //找到方法上的注解 Method[] ms = c.getMethods(); for (Method m:ms) { boolean isMethodExit = m.isAnnotationPresent(Description.class); if (isMethodExit) { //3拿到注解实例 Description description =(Description)m.getAnnotation(Description.class); System.out.println(description); } } //另一种解析方法 for (Method m:ms) { Annotation[] as = m.getAnnotations(); for (Annotation a:as) { if (a instanceof Description) { Description description =(Description)a; System.out.println(description.value()); } } } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 结果:@注解.Description(value=i am interfacer)
*注解实战
需求:有一张用户表,字段包括用户的id,用户名,昵称,年龄,性别,所在城市,邮箱,手机号
方便的对每一个字段或者字段的组合条件进行检索并打印SQL.
package com.zifeng.bean; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface Table { String value(); } package com.zifeng.bean; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface Column { String value(); } package com.zifeng.bean; @Table("user") public class Filter { @Column("id") private int id; @Column("user_name") private String userName; @Column("user_nick") private String nickName; @Column("age") private int age; @Column("user_city") private String city; @Column("user_email") private String email; @Column("user_monile") private String mobile; 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; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Filter [id="); builder.append(id); builder.append(", userName="); builder.append(userName); builder.append(", nickName="); builder.append(nickName); builder.append(", age="); builder.append(age); builder.append(", city="); builder.append(city); builder.append(", email="); builder.append(email); builder.append(", mobile="); builder.append(mobile); builder.append("]"); return builder.toString(); } } package com.zifeng.bean; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Test { public static void main(String[] args) { Filter f1 = new Filter(); f1.setId(8);//查询id为8的用户 Filter f2 = new Filter(); f2.setUserName("Tom"); Filter f3 = new Filter(); f3.setEmail("liu@sina.com"); 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) { StringBuffer sb = new StringBuffer(); //获取class Class c = f.getClass(); //获取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"); //遍历所有的字段 Field[] fArray = c.getDeclaredFields(); for (Field field:fArray) { //处理每个字段对应的sql //拿到字段的名 boolean fExsist = field.isAnnotationPresent(Column.class); if (!fExsist) { continue; } Column column = field.getAnnotation(Column.class); String columnName = column.value(); //拿到字段的值 Object fieldValue = ""; String filedName = field.getName(); String getMethodName = "get"+filedName.substring(0,1).toUpperCase()+filedName.substring(1); try { Method getMethod = c.getMethod(getMethodName); fieldValue = (Object)getMethod.invoke(f); } catch (Exception e) { e.printStackTrace(); } //拼接sql if (fieldValue == null || (fieldValue instanceof Integer && (Integer) fieldValue == 0)) { continue; } sb.append(" and ").append(filedName); if (fieldValue instanceof String) { if (((String) fieldValue).contains(",")) { String[] values = ((String) fieldValue).split(","); sb.append(" in("); for (String v:values) { sb.append("‘"); sb.append(v).append("‘").append(","); } sb.deleteCharAt(sb.length()-1); sb.append(")"); } else { sb.append(" = ").append("‘").append(fieldValue).append("‘"); } } else if (fieldValue instanceof Integer){ sb.append(" = ").append(fieldValue); } } return sb.toString(); } }
执行的结果是:
select * from user where 1=1 and id = 8
select * from user where 1=1 and userName = ‘Tom‘
select * from user where 1=1 and email = ‘liu@sina.com‘
用注解很方便生成sql语句,生成各种表的sql语句,你只需要改变一下bean实体就行了。
标签:
原文地址:http://www.cnblogs.com/airycode/p/4822756.html