很实用几个
例子,在Java开发中,灵活运用可以解决很多问题,比如说持久化实现,还可以配合Struts拦截器解决权限问题,可以控制到方法。
package cn.annotation;
/**
* Define Annotation key words is '@interface' so as class
* If you don't set default value to attribute of field
* when you quote defined Annotation,you should clear and define
* attributes that you define in the Annotation
* @author Administrator
* @since 2011/12/21
*
*/
@interface Myannotation{
public String key();
public String tableName();
public int year();
}
public class AnnotationDemo01 {
@Myannotation(key="yangyang",tableName="talbe",year=23)
public void getInfo(){
System.out.println("自定义Annotation");
}
public static void main(String args[]){
AnnotationDemo01 a1 = new AnnotationDemo01();
a1.getInfo() ;
}
}
package cn.annotation;
/**
* Define Annotation key words is '@interface' so as class
* If you don't set default value to attribute of field
* when you quote defined Annotation,you should clear and define
* attributes that you define in the Annotation
* @author Administrator
*
*/
@interface Myannotation02{
public String key() default "key";
public String tableName() default "table";
public int year() default 0;
}
public class AnnotationDemo02 {
@Myannotation02
public void printInfo(){
System.out.println("自定Annotation,并设置默认值!");
}
public static void main(String[] args) {
AnnotationDemo02 a2 = new AnnotationDemo02();
a2.printInfo();
}
}
package cn.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Annoation范围:
* RetentionPolicy.SOURCE 此Annotation信息只保留在程序源文件中(.java)
* RetentionPolicy.CLASS 此Annotation信息保留在源程序(.java)和编译之后的类文件(.class)中,不加载到Jvm中。默认方式
* RetentionPolicy.RUNTIME 此Annotation信息保留在源程序(.java)和编译之后的类文件(.class)中,运行时加载到Jvm中
* @author Administrator
*
*/
@Retention(value=RetentionPolicy.RUNTIME)
@interface Myannotation04{
public String name() default "yangyang";
}
package cn.annotation;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
/**
* 通过JAVA反射取Annotation
* 只有执行时才会加载到Jvm中,才可以取得Annotation信息
* @author Administrator
*
*/
@Retention(value=RetentionPolicy.RUNTIME)
@interface Myannotation05{
public String name() default "name";
public String sex() default "男";
public int age() default 20;
}
class Simple{
public void printInfo(){
System.out.println("***");
}
}
class SimpleBean extends Simple{
@SuppressWarnings("Unchecked")
@Deprecated
@Override
@Myannotation05(name="张三",sex="男",age=25)
public void printInfo(){
System.out.println("获取Annotaion信息");
}
}
public class AnnotationDemo04 {
public static void main(String[] args) {
Class<SimpleBean> classz = SimpleBean.class;
try{
Method method = classz.getMethod("printInfo", null);
if(method.isAnnotationPresent(Myannotation05.class)){
Myannotation05 info = method.getAnnotation(Myannotation05.class);
System.out.println("姓名:"+info.name()+"、 性别:"+info.sex()+"、 年龄:"+info.age());
}
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}