、定义两个注解类一个是Entity(该注解只能给类用,并且有一个value属性),另一个注解类是Field(该注解只能给属性用,并且有一个value属性)。
2、定义一个Person类,里面定义两个属性name和age。
2、定义一个Person类,里面定义两个属性name和age。
3、使用自定义的注解类,给Person类以及name、age使用,并给注解类中value赋值
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by on 2018/5/10. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) //类 public @interface Entity { //默认值 String value() default "I LOVE U"; }
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by on 2018/5/10. */ @Retention(RetentionPolicy.RUNTIME) @Target( ElementType.FIELD) //参数 public @interface Field { String value() default ""; }
/** * Created by on 2018/5/10. */ @Entity(value = "This is my frist modle") //类 注解 public class Person { @Field(value = "小名") //属性注解 private String name; @Field(value = "18") //属性注解 String age; }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import java.lang.reflect.Field; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Class<Person> personClass = Person.class; Entity annotation = personClass.getAnnotation(Entity.class); Log.d("Test--------------",annotation.value()); try { Class<Person> personClass1 = Person.class; Field name = personClass1.getDeclaredField("name"); com.bawei.xiongda.Field annotation1 = name.getAnnotation(com.bawei.xiongda.Field.class); String value = annotation1.value(); String age = personClass1.getDeclaredField("age").getAnnotation(com.bawei.xiongda.Field.class).value(); Log.d("Test--+++++------------","name:"+value+"age:"+age ); } catch (NoSuchFieldException e) { e.printStackTrace(); } } }