Java反射机制(1):反射机制读取注解

一、ORM(Objective Relation Mapping):对象关系映射

1、类和表结构对应。
2、属性和字段对应。
3、对象和记录对应。

二、类到表的流程

1、写好表名对应的注解。
2、写好表字段对应的注解。
3、将具体的类使用注解。
4、反射机制读取注解的内容。(例如类中注解设定的表名,字段名)
5、读取出来的表名、字段名、类型、长度、是否为主键转换成SQL语句进行操作。(最后两个有专门的框架进行操作)

1、表名注解

	@Target(value= ElementType.TYPE)
	@Retention(RetentionPolicy.RUNTIME)
	public @interface Table {
		String value();
	}

2、字段名注解

	@Retention(RUNTIME)
	@Target(ElementType.FIELD)
	public @interface Field {
		String columnName();
		String type();
		int length();
	}

3、具体的类使用注解

	@Table("tb_student")
	public class Student {
		
		@Field(columnName="id",type="int",length=10)
		private int id;
		
		@Field(columnName="sname",type="varchar",length=10)
		private String studentName;
		
		@Field(columnName="sage",type="int",length=10)
		private int age;
		
		public int getId() {
			return id;
		}
		public void setId(int id) {
			this.id = id;
		}
		public String getStudentName() {
			return studentName;
		}
		public void setStudentName(String studentName) {
			this.studentName = studentName;
		}
		public int getAge() {
			return age;
		}
		public void setAge(int age) {
			this.age = age;
		}
	}

4、反射机制读取注解

	/**
	 * 使用反射读取注解信息,模拟处理注解的流程
	 * @author 鹏鹏
	 *
	 */
	public class Demo01 {
		public static void main(String[] args) throws NoSuchFieldException, SecurityException {
			try {
				Class c = Class.forName("reflectTest.Student");
				
				//获得类的指定注解,打印注解的值,此时为tb_student
				Table table = (Table) c.getAnnotation(Table.class);
				System.out.println(table.value());
				
				
				//获得属性的指定注解
				Field f = c.getDeclaredField("studentName");
				System.out.println(f.getName());
			} catch (ClassNotFoundException e) {
				
				e.printStackTrace();
			}
		}
	}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

coder鹏鹏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值