package fangfa;
public class Person {
@pk
int personid;
@Property("PersonName")
String name;
String sex;
public void eat(){
System.out.println(this.name+"正在吃");
}
@Deprecated
public void eat(String food){
System.out.println(this.name+"正在吃"+food);
}
protected void drink(){
System.out.println(this.name+"正在喝");
}
public Person(String name, String sex) {
super();
this.name = name;
this.sex = sex;
}
public Person() {
super();
}
private Person(String name) {
super();
this.name = name;}
public Person(int personid, String name, String sex) {
super();
this.personid = personid;
this.name = name;
this.sex = sex;}}
package fangfa;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//此注解是用在属性上,可以存活在运行时
@Target(ElementType.FIELD)//用在属性上
@Retention(RetentionPolicy.RUNTIME)
public @interface pk {
}
package fangfa;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)//用在属性上
@Retention(RetentionPolicy.RUNTIME)
public @interface Property {
String value();
//定义的名字和数据库名不一样
}
package fangfa;
import java.lang.reflect.Field;
public class TestAnnotation {
/**
* @param args
*/
@SuppressWarnings("deprecation")
public static void main(String[] args) {
// Person p=new Person();
// p.eat();
// p.eat("老头包子");
Class c=Person.class;
Field[]fs=c.getDeclaredFields();
for(Field f:fs){
//是否使用了某个Annptaton
if(f.isAnnotationPresent(Property.class)){
// System.out.println(f.getName());
//获得f这个属性上的Property注解
Property p=f.getAnnotation(Property.class);
}
}
}
}