Android 注解处理器中的MirroredTypeException异常处理
2020/5/11 23:26:33
本文主要是介绍Android 注解处理器中的MirroredTypeException异常处理,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
在AOP开发中我们经常通过Element
的getAnnotation(Class<A> var1)
方法去获取自定义注解中的传入的属性
例如:
@Target(AnnotationTarget.FIELD) @Retention(AnnotationRetention.SOURCE) @MustBeDocumented annotation class TTEventType(val value: KClass<*>) 复制代码
当我们获取KClass<*>
类型时会出现javax.lang.model.type.MirroredTypeException
,这是因为
The annotation returned by this method could contain an element whose value is of type Class. This value cannot be returned directly: information necessary to locate and load a class (such as the class loader to use) is not available, and the class might not be loadable at all. Attempting to read a Class object by invoking the relevant method on the returned annotation will result in a MirroredTypeException, from which the corresponding TypeMirror may be extracted. Similarly, attempting to read a Class[]-valued element will result in a MirroredTypesException.
处理一
如果硬要从getAnnotation()获取则可以利用MirroredTypeException
public class MirroredTypeException extends MirroredTypesException Thrown when an application attempts to access the Class object corresponding to a TypeMirror. 复制代码
从异常捕获中获取TypeMirror
inline fun <reified T : Annotation> Element.getAnnotationClassValue(f: T.() -> KClass<*>) = try { getAnnotation(T::class.java).f() throw Exception("Expected to get a MirroredTypeException") } catch (e: MirroredTypeException) { e.typeMirror } 复制代码
处理二
我们从AnnotationMirror
下手 在List<? extends AnnotationMirror> getAnnotationMirrors()
方法中获取:
private fun getEventTypeAnnotationMirror(typeElement: VariableElement, clazz: Class<*>): AnnotationMirror? { val clazzName = clazz.name for (m in typeElement.annotationMirrors) { if (m.annotationType.toString() == clazzName) { return m } } return null } private fun getAnnotationValue(annotationMirror: AnnotationMirror, key: String): AnnotationValue? { for ((key1, value) in annotationMirror.elementValues) { if (key1!!.simpleName.toString() == key) { return value } } return null } private fun getMyValue(foo: VariableElement, clazz: Class<*>, key: String): TypeMirror? { val am = getEventTypeAnnotationMirror(foo, clazz) ?: return null val av = getAnnotationValue(am, key) return if (av == null) { null } else { av.value as TypeMirror } } 复制代码
val typeMirror = getMyValue(variableElement,TTEventType::class.java,"value") messager.printMessage(Diagnostic.Kind.NOTE, " --typeMirror-- $typeMirror") 复制代码
参考
Getting Class values from Annotations in an AnnotationProcessor
这篇关于Android 注解处理器中的MirroredTypeException异常处理的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-01-18android.permission.read_media_video
- 2024-01-18android_getaddrinfo failed eai_nodata
- 2024-01-18androidmo
- 2024-01-15Android下三种离屏渲染技术
- 2024-01-09Android 蓝牙使用
- 2024-01-06Android对接华为AI - 文本识别
- 2023-11-15代码安全之代码混淆及加固(Android)
- 2023-11-10简述Android语音播报TTS
- 2023-11-06Android WiFi工具类
- 2023-07-22Android开发未来的出路