java 注解 学习

周末闲来无事,想要研究一下注解方面的知识,曾经看过几次,都忘记了,这次学习下,而且写篇文章记录下,

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); 
} 
} 

看到了,非常easy吧,看了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("
       "+columnDef+ ",");
				String tableCreate = createCommand.substring(0,createCommand.length()-1)+"
 );";
				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;
	}
}


原文地址:https://www.cnblogs.com/bhlsheji/p/4555339.html