在使用Java 6 API编写注释处理器时,我发现需要以特定的方式处理所有映射,但我显然误解了API的用途或如何调用它。这是使我不高兴的代码:
import javax.lang.model.element.Element;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.annotation.processing.ProcessingEnvironment;
...
public String doThing(Element el, ProcessingEnvironment processingEnv) {
// Utilities from the ProcessingEnvironment
Types typeUtils = processingEnv.getTypeUtils();
Elements elementUtils = processingEnv.getElementUtils();
// The type of the element I'm handling
TypeMirror elType = el.asType();
// Compare the element's type to Map
TypeMirror mapType = elementUtils.getTypeElement("java.util.Map").asType();
System.out.println(elType + " > " + mapType + " = " + typeUtils.isSubtype(elType, mapType));
System.out.println(mapType + " > " + elType + " = " + typeUtils.isSubtype(mapType, elType));
System.out.println(elType + " > " + mapType + " = " + typeUtils.isAssignable(elType, mapType));
System.out.println(mapType + " > " + elType + " = " + typeUtils.isAssignable(mapType, elType));
// Compare the element's type to HashMap
TypeMirror hashmapType = elementUtils.getTypeElement("java.util.HashMap").asType();
System.out.println(elType + " > " + hashmapType + " = " + typeUtils.isSubtype(elType, hashmapType));
System.out.println(hashmapType + " > " + elType + " = " + typeUtils.isSubtype(hashmapType, elType));
System.out.println(elType + " > " + hashmapType + " = " + typeUtils.isAssignable(elType, hashmapType));
System.out.println(hashmapType + " > " + elType + " = " + typeUtils.isAssignable(hashmapType, elType));
// Compare the element's type to Object
TypeMirror objectType = elementUtils.getTypeElement("java.lang.Object").asType();
System.out.println(elType + " > " + objectType + " = " + typeUtils.isSubtype(elType, objectType));
System.out.println(objectType + " > " + elType + " = " + typeUtils.isSubtype(objectType, elType));
System.out.println(elType + " > " + objectType + " = " + typeUtils.isAssignable(elType, objectType));
System.out.println(objectType + " > " + elType + " = " + typeUtils.isAssignable(objectType, elType));
}
鉴于此,以下是其输出:
java.util.HashMap<K,V> > java.util.Map<K,V> = false
java.util.Map<K,V> > java.util.HashMap<K,V> = false
java.util.HashMap<K,V> > java.util.Map<K,V> = false
java.util.Map<K,V> > java.util.HashMap<K,V> = false
java.util.HashMap<K,V> > java.util.HashMap<K,V> = true
java.util.HashMap<K,V> > java.util.HashMap<K,V> = true
java.util.HashMap<K,V> > java.util.HashMap<K,V> = true
java.util.HashMap<K,V> > java.util.HashMap<K,V> = true
java.util.HashMap<K,V> > java.lang.Object = true
java.lang.Object > java.util.HashMap<K,V> = false
java.util.HashMap<K,V> > java.lang.Object = true
java.lang.Object > java.util.HashMap<K,V> = false
除了第一个块,我认为这完全说得通,因为我期望HashMap元素可以分配给Map,我也期望HashMap是Map的子类型。
我在这里错过了什么?
types.isAssignable(type, types.erasure(baseGenerifiedType))
(例如,检查类型是否可分配给原始的HashMap
而不是HashMap<?, ?>
)即可。 - user1643723