自定义注解和反射实例
==
/**
* @author 这个例子是说实体和数据库对应表的映射,可以在实体上面使用注解。
*
*/
public class TAnnotationClass {
public static void main(String[] args) throws Exception {
Person p = new Person();
p.personid = 12;
Class c = p.getClass();
Field f = c.getDeclaredFields()[0];
tableFieldName a = f.getAnnotation(tableFieldName.class);
System.out.println("" + a.value());// 获取表的列名称
System.out.println("" + f.get(p));// 获取实体类的值
System.out.println();
}
}
// => 下面是备注接的类
class Person {
@tableFieldName("person_id")
public Integer personid;
}
// => 下面是自定义注解
@Target(ElementType.FIELD)
// 注解是给属性使用的
@Retention(RetentionPolicy.RUNTIME)
// 运行时不消除注解
@Inherited
@interface tableFieldName {
String value() default "";// 注解包含这一个字段
}
==
本文通过一个具体的示例介绍了如何使用自定义注解和Java反射机制来实现实体类和数据库表之间的映射。该示例展示了如何定义自定义注解`tableFieldName`并将其应用于实体类的字段上,然后利用反射读取这些注解信息。
1万+

被折叠的 条评论
为什么被折叠?



