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

  • Post author:
  • Post category:java




一、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();
			}
		}
	}



版权声明:本文为weixin_42701161原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。