最近看了些spring的源码,回来重新看一下反射和注解的一些文档,写了一个小例子,记录一下。
package com.wbk.annotation;
import java.lang.annotation.*;
import java.lang.reflect.Field;
public class ReflectionAndAnnotation {
public static void main(String[] args) throws ClassNotFoundException {
//获得类的class对象
Class c1 = Class.forName("com.wbk.annotation.user");
//获得class对象的注解列表
Annotation[] annotations = c1.getAnnotations();
//打印类注解信息
for (Annotation annotation : annotations) {
System.out.println("注解列表:"+annotation);
}
//获得class的特定注解信息
Annotation annotation = c1.getAnnotation(table_name.class);
System.out.println("user的类注解:"+annotation);
System.out.println("==========================================================");
//获得class对象的属性列表
Field[] declaredFields = c1.getDeclaredFields();
for (Field declaredField : declaredFields) {
//获得属性的注解列表
Annotation[] annotations1 = declaredField.getAnnotations();
for (Annotation annotation1 : annotations1) {
//属性注解列表信息打印
System.out.println(declaredField.getName()+":"+annotation1);
}
}
}
}
/**
* 要映射的user对象,加入自定的类注解和属性注解
*/
@table_name("db_user")
class user {
@field_data(column="user_id",type = "varchar",length = 10)
private int id;
@field_data(column="user_age",type = "varchar",length = 10)
private int age;
@field_data(column="user_name",type = "varchar",length = 10)
private String name;
public user(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
/**
* 自定义类注解
*/
@interface table_name{
String value();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
/**
* 自定义属性注解
*/
@interface field_data{
String column() default "";
String type() default "";
int length() default 0;
}
控制台打印结果:
注解列表:@com.wbk.annotation.table_name(value=db_user)
user的类注解:@com.wbk.annotation.table_name(value=db_user)
==========================================================
id:@com.wbk.annotation.field_data(type=varchar, length=10, column=user_id)
age:@com.wbk.annotation.field_data(type=varchar, length=10, column=user_age)
name:@com.wbk.annotation.field_data(type=varchar, length=10, column=user_name)
标签:java,name,自定义,age,id,user,注解,annotation From: https://www.cnblogs.com/zenigeba/p/16652641.html