您的位置:首页 > 编程语言 > Java开发

JAVA自定义注解使用

2016-10-30 17:15 411 查看
说到注解 在java中我们经常会看到@Override,@Deprecated,@SuppressWarnings这些注解。这些都是JDK自带的注解

关于自定义注解:



1.使用@interface关键字定义注解

2.成员以无参方式声明

3.成员可以使用default指定一个默认值

4.如果只有一个成员  成员名必须为value().使用时 可以忽略=号

元注解:

@Target  表示注解的作作用域。ElementType参数有

ElementType.TYPE 类,接口等
ElementType.METHOD 方法声明

ElementType.CONSTRUCTOR 构造方法声明

ElementType.FIELD 字段声明

ElementType.LOCAL_VARIABLE 局部变量声明

ElementType.PACKAGE 包声明

ElementType.PARAMETER 参数声明
@Retention表示注解的声明周期,可能用到的RetentionPolicy参数有

RetentionPolicy.SOURCE 源码注解(注解将被编译器丢弃)

RetentionPolicy.CLASS 编译时注解(注解在class文件可用,但会被VM丢弃)
RetentionPolicy.RUNTIME 运行时注解(运行时保留注解,因此可以使用java反射机制读取注解信息)

@Inherited 允许子类继承父类的注解

@Documented将注解包含在javadoc中

自定义注解实战
项目需求



我们分别为表名和字段名新建注解
Table注解  作用域在类@Target(ElementType.TYPE),生命周期为@Retention(RetentionPolicy.RUNTIME)
package com.susu;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Table {
String value();
}


Column注解,作用域在字段名@Target(ElementType.FIELD)生命周期为@Retention(RetentionPolicy.RUNTIME)

package com.susu;

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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Column {
String value();
}


User实体类。
package com.susu;

@Table("user")
public class User {
@Column("id")
private int id;
@Column("username")
private String username;
@Column("nickname")
private String nickname;
@Column("age")
private int age;
@Column("gender")
private String gender;
@Column("city")
private String city;
@Column("email")
private String email;
@Column("phoneNumber")
private String phoneNumber;

public User() {
super();
// TODO Auto-generated constructor stub
}

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 getGender() {
return gender;
}

public void setGender(String gender) {
this.gender = gender;
}

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 getPhoneNumber() {
return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}

}


下面是测试类
package com.susu;

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

public class Test {
public static void main(String[] args) {
User user1=new User();
user1.setNickname("小明");
user1.setAge(10);

User user2=new User();
user2.setUsername("张三");
User user3=new User();
user3.setEmail("1142819049@qq.com");
user3.setCity("北京");
query(user1);
query(user2);
query(user3);
}

@SuppressWarnings({ "rawtypes", "unchecked" })
private static void query(Object obj) {
StringBuilder sb=new StringBuilder();
Class c=obj.getClass();
//如果类不包含@Table注解 结束
if(!c.isAnnotationPresent(Table.class)){
return ;
}
//获得表名
Table table= (Table) c.getAnnotation(Table.class);
sb.append("select * from "+table.value()+" where 1 = 1");
Field fields[]=c.getDeclaredFields();
for (Field field : fields) {
//如果该字段不包含@Column注解  遍历下一个
if(!field.isAnnotationPresent(Column.class)){
continue;
}
//获得字段名

Column column=field.getAnnotation(Column.class);
String columnName=column.value();
String fieldName=field.getName();
//获取该字段的get方法
String methodName="get"+fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1);
try {
Method method=c.getDeclaredMethod(methodName);
Object o =method.invoke(obj);
if(o==null||(o instanceof Integer&&(Integer)o==0)){
continue;
}
//拼装sql
if(o instanceof String){
sb.append(" and "+columnName+" = '"+o+"'");
}else if(o instanceof Integer){
sb.append(" and "+columnName+" = "+o);
}

} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(sb.toString());
}
}


运行结果:



我们可以使用@Table和@Column这两个注解 对新的表 新的字段进行拼装sql查询语句
比如,新表
package com.susu;
@Table("Department")
public class Department {
@Column("id")
private int id;
@Column("leader")
private String leader;
@Column("city")
private String name;
@Column("city")
private String city;
public Department() {
super();
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLeader() {
return leader;
}
public void setLeader(String leader) {
this.leader = leader;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}

}
在测试类里面继续调用
Department dep1=new Department();
dep1.setId(5);
dep1.setLeader("张三");
dep1.setCity("上海");
Department dep2=new Department();
dep2.setCity("成都");
query(dep1);
query(dep2);


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: