Android 代码注解初学者
1、定义遍历注解类。
public class BindData { /** * 绑定Activity */ public static void bind(final Activity activity) { Class annotationParent = activity.getClass(); Field[] fields = annotationParent.getDeclaredFields(); // 找到类里面所有的方法 if (fields.length > 0) { for (Field field : fields) { try { field.setAccessible(true); if (field.get(activity) != null) { continue; } ViewData bind = field.getAnnotation(ViewData.class); if (bind != null) { Log.e("wade", field.getType().getName()); List<String> data = new ArrayList<>(); data.add("12341243"); data.add("zhansan"); field.set(activity, data); } } catch (Exception e) { e.printStackTrace(); } } } } }
2、定义需要注解类的名称
@Retention(RUNTIME) @Target(FIELD) public @interface ViewData { }
3、在主activity中绑定遍历的类,初始化data数据。
class MainActivity : AppCompatActivity() { @ViewData var data: List<String>? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) BindData.bind(this) Log.i(javaClass.name, data.toString()) } }