博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java之Annotation学习
阅读量:6969 次
发布时间:2019-06-27

本文共 2144 字,大约阅读时间需要 7 分钟。

hot3.png

相关概念:

定义注解

package cn.baokx.annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(value={ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)public @interface MyTableAnnotation {	String value();}
package cn.baokx.annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(value={ElementType.FIELD})@Retention(RetentionPolicy.RUNTIME)public @interface MyFieldAnnotation {	String columnName();	String type();}
package cn.baokx.annotation;@MyTableAnnotation("TBL_STUDENT")public class Student {	@MyFieldAnnotation(columnName="NAME",type="VARCHAR")	private String name;	@MyFieldAnnotation(columnName="AGE",type="INT")	private int age;	public String getName() {		return name;	}	public void setName(String name) {		this.name = name;	}	public int getAge() {		return age;	}	public void setAge(int age) {		this.age = age;	}	}

package cn.baokx.annotation;import java.lang.reflect.Field;public class Main {	public static void main(String[] args) throws NoSuchFieldException, SecurityException, ClassNotFoundException {		Student stu = new Student();		stu.setName("baokx");		stu.setAge(30);		handler(stu);	}		public static void handler(Student stu) throws NoSuchFieldException, SecurityException, ClassNotFoundException{		Class clazz = stu.getClass();		MyTableAnnotation mta = (MyTableAnnotation) clazz.getAnnotation(MyTableAnnotation.class);		System.out.println("tableName:"+mta.value());				Field f = clazz.getDeclaredField("name");		MyFieldAnnotation mfa = f.getAnnotation(MyFieldAnnotation.class);		System.out.println("columnName:"+mfa.columnName());		System.out.println("type:"+mfa.type());		System.out.println("value:"+stu.getName());				f = clazz.getDeclaredField("age");		mfa = f.getAnnotation(MyFieldAnnotation.class);		System.out.println("columnName:"+mfa.columnName());		System.out.println("type:"+mfa.type());		System.out.println("value:"+stu.getAge());	}}

转载于:https://my.oschina.net/u/1427708/blog/710662

你可能感兴趣的文章
this关键字
查看>>
Python中字符串和datetime
查看>>
ng-Cordova插件之fileTransfer的使用
查看>>
基于struts1.框架的异常处理方案
查看>>
浅谈 Qt 内存管理
查看>>
【Qt】Qt之密码框不可选中、复制、粘贴、无右键菜单等【转】
查看>>
Flume中关于HDFS的sink配置
查看>>
Idea 社区版开发指南-1
查看>>
date命令转换unix时间戳
查看>>
/usr/lib目录属性更改引发的蝴蝶效应
查看>>
比禅道好用的项目管理 项目管理工具Redmine 各功能测试
查看>>
org.apache.commons 常用工具类
查看>>
TabHost的使用
查看>>
OpenGL超级宝典笔记——颜色
查看>>
shell 命令学习
查看>>
身份证号码怎么玩
查看>>
Android UI生成随机颜色
查看>>
RabbitMQ官方中文入门教程(PHP版) 第四部分:路由(Routing)
查看>>
DataURL与File,Blob,canvas对象之间的互相转换的Javascript
查看>>
Android Tips 8(To run dex in process, the Gradle daemon needs a larger heap)
查看>>