注解

来源:互联网 发布:福昕pdf软件套装 编辑:程序博客网 时间:2024/06/05 06:34
package fangfa;public class Person {@pkint personid;@Property("PersonName")String name;String sex;public void eat(){System.out.println(this.name+"正在吃");}@Deprecatedpublic 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){//是否使用了某个Annptatonif(f.isAnnotationPresent(Property.class)){//System.out.println(f.getName());//获得f这个属性上的Property注解Property p=f.getAnnotation(Property.class);}}}}