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

Java 注解

2016-07-24 00:00 465 查看
#Java注解
##一.概念
###1.元注解

@Documented

此注解用于将描述其它类型的annotation可以被文档化。

//源码
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public [[[[@interface](http://my.oschina.net/u/996807)](http://my.oschina.net/u/996807)](http://my.oschina.net/u/996807)](http://my.oschina.net/u/996807) Documented {
}


@Target
此注解用于说明了Annotation所修饰的对象范围
//源码
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
ElementType[] value();
}
ElementType有:
TYPE:类,接口,枚举类型
FIELD:域
METHOD:方法
PARAMETER:参数
CONSTRUCTOR:构造器
LOCAL_VARIABLE:局部变量
PACKAGE:包

@Retention

//源码
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
RetentionPolicy value();
}

RetentionPolicy有:
SOURCE:只保存在源文件中
CLASS:只保存在class文件中
RUNTIME:此注解会在class字节码文件中存在,在运行时可以通过反射获取到

@Inherited

@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。

//源码
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited {
}

###2.自定义注解

自定义注解是以@interface为标志的。如同一个接口的定义,这里面定义的每个方法名,就是使用注解时候的元素名,方法的返回值就是元素的类型,可以利用default来声明默认值,不过对于非基本类型,不能设置为null为默认值,一般对于字符串使用空字符串作为其默认值。
####2.1定义注解
代码如下:

//说明该注解将被包含在javadoc中
@Documented
//这个注解可以是类注解,也可以是方法的注解
@Target({ ElementType.TYPE, ElementType.METHOD })
//定义的这个注解是注解会在class字节码文件中存在,在运行时可以通过反射获取到。
@Retention(RetentionPolicy.RUNTIME)
//子类可以继承父类中的该注解
@Inherited

public @interface ReportAnnotation {
// 为注解定义一个方法即为注解定义了一个元素,返回的默认值为0
public int index() default 0;
}

####2.2使用注解

代码如下:

public class BaseModel {

private Integer id;
private String name;
private String address;
public BaseModel(Integer id,String name,String address) {

this.id=id;
this.name=name;
this.address=address;
}

@ReportAnnotation(index=0)
public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}
@ReportAnnotation(index=1)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ReportAnnotation(index=2)
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}

}

####2.3注解处理器

代码如下:

//ReportAnnotationProcessor类,运用反射,运行过程动态获取类信息。

public class ReportAnnotationProcessor{
public void  parseMethod(Object obj) throws Exception {
// 得到目标类的方法集
final Method[] methods = obj.getClass().getDeclaredMethods();

for (final Method method : methods) {
// 获取方法上的注解,同时判断是否存在
final ReportAnnotation my = method.getAnnotation(ReportAnnotation.class);
if (null != my) {
Object object=method.invoke(obj);
System.out.println(my.index()+":"+object.toString());
}
}
//
}
}

//Client类

public class Client {
public static void main(String args[]){

BaseModel baseModel1=new BaseModel(1, "lily", "ww");
BaseModel baseModel2=new BaseModel(2, "Bob", "mm");
List<BaseModel> list=new ArrayList<BaseModel>();
list.add(baseModel2);
list.add(baseModel1);
for(BaseModel bm:list){
final ReportAnnotationProcessor ra=new ReportAnnotationProcessor();
try {
ra.parseMethod(bm);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

输出结果:

2:mm

1:Bob

0:2

2:ww

1:lily

0:1

###3.模拟ORM实现
####3.1 ORM概念
ORM-对象关系映射,将数据库中的表和内存中的对象建立了很好的映射关系。
####3.2 模拟ORM代码实现

注解类Table

package orm;

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

@Target({ElementType.TYPE,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
public String tablename();
}

注解类TableField

package orm;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface TableField {
public String name();
public boolean isPrimaryKey() default false;
}

VO类People

package orm;
@Table(tablename="people")
public class People {

@TableField(name="people_id",isPrimaryKey = true)
public Integer id;

@TableField(name="people_name")
public String name;

@TableField(name="people_age")
public Integer age;

public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}

BaseOrm类

package orm;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public abstract class BaseOrm<T> {
// 保存数据
public void save(T t) {
StringBuffer sql = new StringBuffer();
sql.append("insert into ");
// 获得注解Table类
Table table = t.getClass().getAnnotation(Table.class);
if (table != null) {
sql.append(table.tablename());
}
// 获得类的共有属性
Field field[] = t.getClass().getFields();
sql.append(" (");
StringBuffer valueSql = new StringBuffer();
String temp = "";
for (Field f : field) {
// 获得属性注解类TableField
TableField tableField = f.getAnnotation(TableField.class);
if (tableField != null) {
// 获得字段第一个字母大写
String firstLetter = f.getName().substring(0, 1).toUpperCase();
// 转换成字段的get方法
String getMethodName = "get" + firstLetter + f.getName().substring(1);
try {
Method getMethod = t.getClass().getMethod(getMethodName, new Class[] {});
// 这个对象字段get方法的值
Object value = getMethod.invoke(t, new Object[] {});
// 如果属性类型为String类型
if (f.getType().getName().equals(java.lang.String.class.getName())) {
valueSql.append(temp + "'" + value + "'");
} else {
valueSql.append(temp + value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (tableField != null) {
sql.append(temp + tableField.name());
} else {
sql.append(temp + f.getName());
}
temp = ",";
}
sql.append(")values(");
sql.append(valueSql);
sql.append(")");
System.out.println(sql.toString());
}
}

PeopleDAO类

package orm;

public class PeopleDAO extends BaseOrm<People>{

}

Client类

package orm;

public class Client {

public static void main(String [] args){
People people=new People();
people.setId(1);
people.setAge(23);
people.setName("Lily");
PeopleDAO peopleDAO=new PeopleDAO();
peopleDAO.save(people);
}
}

输出结果

insert into people(people_id,people_name,people_age)values(1,'Lily',23)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: