/**
* Created by micki on 2017/11/24.
* activity布局id注解
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface BindContentView {
int value();
}
2. 创建好注解类后,要解析处理这个注解类
/**
* Created by micki on 2017/11/24.
* 注解处理
*/
public class AnnotationUtils {
public static void injectContentView(Activity activity) {
Class a = activity.getClass();
if (a.isAnnotationPresent(BindContentView.class)) { // 获取注解类
BindContentView bindContentView = (BindContentView) a.getAnnotation(BindContentView.class);
int layoutId = bindContentView.value(); // 得到传入注解类布局id
try {
Method method = a.getMethod("setContentView", int.class);
method.setAccessible(false);
method.invoke(activity, layoutId);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
/**
* Created by micki on 2017/11/24.
* activity布局id注解
*/
@kotlin.annotation.Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FILE)
annotation class BindContentViewK(val value: Int)
/**
* Created by micki on 2017/11/24.
* 注解处理
*/
object AnnotationUtilsK {
fun injectContentView(activity: Activity) {
val a = activity.javaClass
if (a.isAnnotationPresent(BindContentViewK::class.java)) {
val contentView = a.getAnnotation(BindContentViewK::class.java) as BindContentViewK
val layoutId = contentView.value
try {
val method = a.getMethod("setContentView", Int::class.javaPrimitiveType)
method.isAccessible = false
method.invoke(activity, layoutId)
} catch (e: NoSuchMethodException) {
e.printStackTrace()
} catch (e: IllegalAccessException) {
e.printStackTrace()
} catch (e: InvocationTargetException) {
e.printStackTrace()
}
}
}
}