tor*_*omp 6 java reflection annotation-processing
我刚刚进入这里的javax AnnotationProcessing,并遇到了一个丑陋的案例.我将在一系列描述我学习过程的伪代码行中进行说明:
MyAnnotation ann = elementIfound.getAnnotation(MyAnnotation.class);
// Class<?> clazz = ann.getCustomClass(); // Can throw MirroredTypeException!
// Classes within the compilation unit don't exist in this form at compile time!
// Search web and find this alternative...
// Inspect all AnnotationMirrors
for (AnnotationMirror mirror : element.getAnnotationMirrors()) {
if (mirror.getAnnotationType().toString().equals(annotationType.getName())) {
// Inspect all methods on the Annotation class
for (Entry<? extends ExecutableElement,? extends AnnotationValue> entry : mirror.getElementValues().entrySet()) {
if (entry.getKey().getSimpleName().toString().equals(paramName)) {
return (TypeMirror) entry.getValue();
}
}
return null;
}
}
return null;
Run Code Online (Sandbox Code Playgroud)
问题是,现在我发现如果客户端代码包含类似java.lang.String或java.lang.Object作为Class参数的核心类,则此行:
return (TypeMirror) entry.getValue();
Run Code Online (Sandbox Code Playgroud)
...导致a ClassCastException,因为AnnotationProcessor环境足以Class在这种情况下实际检索对象.
我已经想出如何TypeMirror在没有的情况下Class做我需要做的所有事情- 我现在需要在我的代码中处理它们吗?有没有办法TypeMirror从Class对象中获取?因为我找不到一个
tor*_*omp 10
我遇到这个问题的解决方案是使用ProcessingEnvironment将生成的Class对象强制转换为TypeMirrors,在我得到类而不是TypeMirrors的情况下.这似乎运作得相当好.
AnnotationValue annValue = entry.getValue();
if (annValue instanceof TypeMirror) {
return (TypeMirror) annValue;
}
else {
String valString = annValue.getValue().toString();
TypeElement elem = processingEnv.getElementUtils().getTypeElement(valString);
return elem.asType();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4420 次 |
| 最近记录: |