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

java 注解 学习

2014-08-10 00:11 344 查看
周末闲来无事,想要研究一下注解方面的知识,以前看过几次,都忘记了,这次学习下,并且写篇文章记录下,

1、元注解

元注解是指注解的注解。包括 @Retention @Target @Document @Inherited四种。

1.1、@Retention: 定义注解的保留策略

Java代码

复制代码代码如下:

@Retention(RetentionPolicy.SOURCE) //注解仅存在于源码中,在class字节码文件中不包含

@Retention(RetentionPolicy.CLASS) //默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,

@Retention(RetentionPolicy.RUNTIME)//注解会在class字节码文件中存在,在运行时可以通过反射获取到



1.2、@Target:定义注解的作用目标


Java代码

复制代码代码如下:

@Target(ElementType.TYPE) //接口、类、枚举、注解

@Target(ElementType.FIELD) //字段、枚举的常量

@Target(ElementType.METHOD) //方法

@Target(ElementType.PARAMETER) //方法参数

@Target(ElementType.CONSTRUCTOR) //构造函数

@Target(ElementType.LOCAL_VARIABLE)//局部变量

@Target(ElementType.ANNOTATION_TYPE)//注解

@Target(ElementType.PACKAGE) ///包

elementType 可以有多个,一个注解可以为类的,方法的,字段的等等

1.3、@Document:说明该注解将被包含在javadoc中

1.4、@Inherited:说明子类可以继承父类中的该注解


2、注解的自定义

Java代码

复制代码 代码如下:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface HelloWorld {
public String name() default "";
}




3、注解的使用,测试类


Java代码

复制代码 代码如下:

public class SayHello {
@HelloWorld(name = " 小明 ")
public void sayHello(String name) {
System.out.println(name + "say hello world!");
}//www.heatpress123.net
}


4、解析注解

java的反射机制可以帮助,得到注解,代码如下:

Java代码

复制代码 代码如下:

public class AnnTest {
public void parseMethod(Class<?> clazz) {
Object obj;
try {
// 通过默认构造方法创建一个新的对象
obj = clazz.getConstructor(new Class[] {}).newInstance(
new Object[] {});
for (Method method : clazz.getDeclaredMethods()) {
HelloWorld say = method.getAnnotation(HelloWorld.class);
String name = "";
if (say != null) {
name = say.name();
System.out.println(name);
method.invoke(obj, name);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
AnnTest t = new AnnTest();
t.parseMethod(SayHello.class);
}
}


看到了,很简单吧,看了java编程思想里面有个复杂点的例子,我们来温习一遍,他是用注解实现一个创建数据库的例子。

先写一个数据库名字的注解,用来读取数据库的名字:

package com.bin.annotation;
import java.lang.annotation.*;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DBTable {
public String name() default"";
}


创建一个integer类型的字段:

package com.bin.annotation;
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 SQLInteger {
String name() default""; //默认为空
Constraints constraints() default @Constraints; //字段的其他类型定义
}


创建一个String 类型的字段:

package com.bin.annotation;

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 SQLString {
int value() default 0;
String name() default "";
Constraints constraints() default @Constraints;
}


一些其他定义

package com.bin.annotation;
import java.lang.annotation.*;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Constraints {
boolean primaryKey() default false;
boolean allowNull() default true;
boolean unique() default false;
}


创建一个注解的bean
package com.bin.annotation;

@DBTable(name="MEMBER")
public class Member {
@SQLString(30)
String firstName;
@SQLString(50)
String lastName;
@SQLInteger
Integer age;
@SQLString(value=30,constraints=@Constraints(primaryKey=true))
String handle;
static int memberCount;
public String toString(){return handle.toString();}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getHandle() {
return handle;
}
public void setHandle(String handle) {
this.handle = handle;
}
}


最后让我们解析这个注解吧:

package com.bin.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class TableCreator {
public static void main(String[] args) throws ClassNotFoundException{
Class<?> cl =Member.class;
DBTable dbtalbe=cl.getAnnotation(DBTable.class);
String tableName = dbtalbe.name();
if(tableName.length() <1)
tableName=cl.getName().toUpperCase();
List<String> columnDefs = new ArrayList<String>();
for(Field filed : cl.getDeclaredFields()){
String columnName = null;
Annotation[] anns = filed.getDeclaredAnnotations();
if(anns.length < 1)
continue;
if(anns[0] instanceof SQLInteger){
SQLInteger sInt = (SQLInteger)anns[0];
if(sInt.name().length() < 1)
columnName = filed.getName().toUpperCase();
else
columnName = sInt.name();
columnDefs.add(columnName + " INT " + getConstraints(sInt.constraints()));
}
if(anns[0] instanceof SQLString){
SQLString sString =(SQLString) anns[0];
if(sString.name().length() <1){
columnName = filed.getName().toUpperCase();
}else
columnName =sString.name();
columnDefs.add(columnName + " VARCHAR("+sString.value()+") " +getConstraints(sString.constraints()));
}
}
StringBuilder createCommand = new StringBuilder("CREATE TABLE" +tableName + "(");
for(String columnDef : columnDefs)
createCommand.append("\n       "+columnDef+ ",");
String tableCreate = createCommand.substring(0,createCommand.length()-1)+"\n );";
System.out.print(tableCreate);
}
private static String getConstraints(Constraints con){
String constraints = "";
if(!con.allowNull()){
constraints +="NOT NULL";
}
if(!con.primaryKey()){
constraints +="PRIMARY KEY";
}
if(!con.unique()){
constraints +="UNIQUE";
}
return constraints;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: