学习注解的目的:
1、能够读懂别人的代码,特别是框架相关的代码2、让编程更加简介,代码更加清晰
3、让别人高看一眼
注解概念:
1.5提供了源程序中元素关联任何信息和任何元数据的途径和方法JDK自带注解:
1. @Override 覆盖了父类的方法2. @Deprecated表示方法已经过时,
3. @SuppressWarnings("deprecation")用于通知java编译器忽略特定的编译警告
注解按照运行机制来分类,分为
源码注解:只在源码中存在,编译后就不存在了
编译时注解:存在于源码和.class文件中。如:@Override
运行时注解:在运行阶段还会起作用的注解
自定义注解
@Target({ElementType.METHOD,ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented 这四行为元注解
public @interface Description{ //使用@interface关键字定义注解
String desc(); //成员以无参无异常方式声明
String author();
int age() default 18; //可以用default为成员制定一个默认值
}
1 @Target 注解的使用范围
CONSTRUCTOR(构造器), FIELD(域), LOCAL_VARIABLE(局部变量), METHOD(方法)
PACKAGE(包), PARAMETER(参数), TYPE(类、接口(包括注解类型) 或enum声明)
2 @Retention:注解的生命周期 SOURCE:在源文件中有效(即源文件保留),
CLASS:在class文件中有效(即class保留)
RUNTIME:在运行时有效(即运行时保留)
3.@Inherited 允许子类继承
4.成员类型是受限的,合法的类型包括原始类型,String,Class,Annotation,Enumeration
如果注解只有一个成员,则成员名必须取名为value(),在使用时可以忽略成员名和赋值号(=)
注解类可以没有成员,没有成员的注解称为标识注解
使用自定义注解
语法:@<注解名>(<成员名1>=<成员值1>,<成员名2>=<成员值2>,...)Description
@Description(desc="I am" ,author="mooc",age=18)
public String eyeColor(){
return "red";
}
解析注解
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
/**
* 自定义拦截器
* @author grace
*
*/
@SuppressWarnings("serial")
public class LimitInterceptor extends MethodFilterInterceptor{
public String doIntercept(ActionInvocation invocation) throws Exception {
//获取请求的action对象
Object action=invocation.getAction();
//获取请求的方法的名称
String methodName=invocation.getProxy().getMethod();
//获取action中的方法的封装类(action中的方法没有参数)
Method method=action.getClass().getMethod(methodName, null);
//获取request对象
HttpServletRequest request=ServletActionContext.getRequest();
//检查注解
boolean flag=isCheckLimit(request,method);
if(!flag){
//没有权限,通过struts2转到事先定义好的页面
return "popmsg_popedom";
}
//有权限,可以调用action中的方法
String returnvalue=invocation.invoke();
return returnvalue;
}
public boolean isCheckLimit(HttpServletRequest request, Method method) {
if(method==null){
return false;
}
//获取当前的登陆用户
SysUser sysUser=SessionUtils.getSysUserFormSession(request);
if(sysUser==null){
return false;
}
//如果用户的权限组为空
if(sysUser.getSysRole()==null){
return false;
}
//获取当前登陆用户的权限组id
String roleId=sysUser.getSysRole().getId();
//处理注解
/*
* @Limit(module="group",privilege="list")
public String list(){
....
}
*/
//判断用户请求的method上面是否存在注解
boolean isAnnotationPresent= method.isAnnotationPresent(Limit.class);
//不存在注解
if(!isAnnotationPresent){
return false;
}
//存在注解,拿到由Limit类写的注解
Limit limit=method.getAnnotation(Limit.class);
//获取注解上的值
String module=limit.module(); //模块名称
String privilege=limit.privilege(); //操作名称
/**
* 如果登陆用户的权限组id+注解上的@Limit(module="group",privilege="list")
* * 在sys_popedom_privilege表中存在 flag=true;
* * 在sys_popedom_privilege表中不存在 flag=false;
*/
boolean flag=false;
//通过自己封装的方法拿到操作权限的业务层对象
ISysPopedomPrivilegeService sysPopedomPrivilegeService=
(ISysPopedomPrivilegeService)ServiceProvinder.getService(ISysPopedomPrivilegeService.SERVICE_NAME);
//查询sys_popedom_privilege表中的所有的数据
//因为后面用到二级缓存,因此这里直接查询出所有的操作权限,而不是通过登陆用户的权限组来查询
List<SysPopedomPrivilege> list=sysPopedomPrivilegeService.findAllSysPopedomPrivileges();
if(list!=null&&list.size()>0){
for(int i=0;i<list.size();i++){
SysPopedomPrivilege s=list.get(i);
if(s!=null){
//判断登陆用户是否拥有该方法的权限:如果登陆用户的roleId和登陆用户访问的方法
//的注释中的module和privilege(例如@Limit(module="group",privilege="list")),这三个字段
//在sys_popedom_privilege表中有记录与之对应,则代表该用户拥有权限访问此方法
if(roleId.equals(s.getId().getRoleId())&&module.equals(s.getId().getPopedomModule())
&&privilege.equals(s.getId().getPopedomPrivilege())){
flag=true;
break;
}
}
}
}
return flag;
}
}
Description.java 定义
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.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME) //运行时
@Inherited //只作用于继承类的类注解,对接口不起作用
@Documented
public @interface Description{ //使用@interface关键字定义注解
String value();
}
ParseAnn.java 解析注解
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
@Description("I am Class Description")
public class ParseAnn {
@Description("I am Method Description")
public void sing() {
}
public static void main(String[] args){
try {
//1.使用类加载器加载类
Class c=Class.forName("Child");
//2.找到类上面的注解
boolean isExist=c.isAnnotationPresent(Description.class);
if(isExist){
//3.拿到注解实例
Description d=(Description) c.getAnnotation(Description.class);
System.out.println(d.value());
}
//4.找到方法上的注解
Method[] ms=c.getMethods();
for(Method m:ms){
boolean isMExist=m.isAnnotationPresent(Description.class);
if(isMExist){
Description dM=(Description) m.getAnnotation(Description.class);
System.out.println(dM.value());
}
}
//另外一种解析方法
for(Method m:ms){
Annotation []as=m.getAnnotations();
for(Annotation a:as){
if(a instanceof Description){
Description d=(Description)a;
System.out.println(d.value());
}
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
项目实战
Table.java 类注解
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();
}
Column.java 字段注解
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();
}
Filter.java 实体类 使用注解
@Table("user")
public class Filter {
@Column("id")
private int id;
@Column("userName")
private String userName;
@Column("email")
private String email;
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Test.java 解析注解
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Test {
public static String query(Object f){
StringBuilder sb=new StringBuilder();
//1.获取Class
Class c=f.getClass();
//2.获取Table的名字
boolean isExist=c.isAnnotationPresent(Table.class);
if(!isExist){
return null;
}
Table t=(Table) c.getAnnotation(Table.class);
String tableName=t.value();
sb.append("select * form ").append(tableName).append(" where 1=1 ");
//3.遍历所有的字段
Field[] fArray=c.getDeclaredFields();
for(Field field:fArray){
//处理每个字段对应的sql
boolean fExist=field.isAnnotationPresent(Column.class);
if(! fExist){
continue;
}
Column column=field.getAnnotation(Column.class);
String columnName=column.value(); //数据库字段名
String fieldName=field.getName();
String getMethodName="get"+fieldName.substring(0, 1).toUpperCase()
+fieldName.substring(1); //get方法名
Object fieldValue=null;
try {
Method getMethod=c.getMethod(getMethodName);
fieldValue=getMethod.invoke(f);//类字段值
} catch (Exception e) {
e.printStackTrace();
}
//拼装sql
if(fieldValue==null || ((fieldValue instanceof Integer)&&((Integer)fieldValue==0)))
continue;
sb.append(" and ").append(fieldName);
if(fieldValue instanceof String){
if(((String) fieldValue).contains(",")){ //email
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("'").append(fieldValue).append("'");
}else{
sb.append("=").append(fieldValue);
}
}
System.out.println(sb.toString());
return sb.toString();
}
public static void main(String[] args){
Filter f1=new Filter();
f1.setId(10);
Filter f2=new Filter();
f2.setUserName("lucy");
Filter f3=new Filter();
f3.setEmail("liu@sina.com,zh@163.com,7777@qq.com");
String sql1=query(f1);
String sql2=query(f2);
String sql3=query(f3);
}
}