문제

For example I have a Field that I got through reflection. This field has annotation on it. I use

field.getAnnotation(CustomAnnotation.class)

to get one. Can I use it as key in hash map? I mean of cause I can, but will this key be unique for the Field?


I want HashMap<CustomAnnotation, Integer> where Integer value is an index of last used element in a collection that CustomAnnotation has:

@CustomAnnotation(values={"ONE", "TWO"})
도움이 되었습니까?

해결책

You can use Annotation instances as HashMap keys. The interface defines exactly how equals and hashCode should work. In essence they are equal ...

... if the specified object represents an annotation that is logically equivalent to this one.

However, I am not sure this is what you want.

In particular, if you have the same @CustomAnnotation(x=123) on two different fields, only one of those can go into the map.

Don't you want to key on the Field and get the annotation back?

FWIW, Field (and Class, and Method) can all be used as keys, with "good semantics" (considered equal if refering to the same object).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top