1、自定义一个注解类
package com.jingzx.anotation_pj;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Function: 自定义的注解类
* Created by TianMing.Xiong on 2017/9/14.
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation {
String value() default "default value";
}
2、使用这个注解类
package com.jingzx.anotation_pj;
/**
* Function: 使用自定义的注解
* Created by TianMing.Xiong on 2017/9/14.
*/
public class UseMyAnnotation {
@MyAnnotation("三小灵犀")
private String filedName ;
}
3、解析被标注的字段的注解值
package com.jingzx.anotation_pj;
import android.util.Log;
import java.lang.reflect.Field;
/**
* Function: 解析我的注解获取标注的值
* Created by TianMing.Xiong on 2017/9/14.
*/
public class ParseMyAnnotation {
public static String parseMyAnnotation(Class<?> clazz){
Field[] declaredFields = clazz.getDeclaredFields();
for (Field field: declaredFields ) {
if(field.isAnnotationPresent(MyAnnotation.class)){
MyAnnotation filedName = (MyAnnotation) field.getAnnotation(MyAnnotation.class);
Log.e("xtm", "我属性的值: "+filedName.value() );
return filedName.value() ;
}
}
return null ;
}
}
4、测试是否成功
xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.jingzx.anotation_pj.MainActivity">
<Button
android:text="获取注解上的值"
android:onClick="getAnnotationValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/tv_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</LinearLayout>
MainActivity
package com.jingzx.anotation_pj;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void getAnnotationValue(View v){
String value = ParseMyAnnotation.parseMyAnnotation(UseMyAnnotation.class);
TextView textView = (TextView) findViewById(R.id.tv_value);
textView.setText(value+"");
}
}
执行效果: