Skip to content

Commit d071802

Browse files
kashikekevinb9n
authored andcommitted
Add a .withAnnotation() method to simplify creating keys with different annotations.
Closes #1108 ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=313246519
1 parent c83404b commit d071802

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

core/src/com/google/inject/Key.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,30 @@ public <T> Key<T> ofType(TypeLiteral<T> type) {
290290
return new Key<T>(type, annotationStrategy);
291291
}
292292

293+
/**
294+
* Returns a new key of the same type with the specified annotation.
295+
*
296+
* <p>This is equivalent to {@code Key.get(key.getTypeLiteral(), annotation)} but may be more
297+
* convenient to use in certain cases.
298+
*
299+
* @since vNext
300+
*/
301+
public Key<T> withAnnotation(Class<? extends Annotation> annotationType) {
302+
return new Key<T>(typeLiteral, strategyFor(annotationType));
303+
}
304+
305+
/**
306+
* Returns a new key of the same type with the specified annotation.
307+
*
308+
* <p>This is equivalent to {@code Key.get(key.getTypeLiteral(), annotation)} but may be more
309+
* convenient to use in certain cases.
310+
*
311+
* @since vNext
312+
*/
313+
public Key<T> withAnnotation(Annotation annotation) {
314+
return new Key<T>(typeLiteral, strategyFor(annotation));
315+
}
316+
293317
/**
294318
* Returns true if this key has annotation attributes.
295319
*

core/test/com/google/inject/KeyTest.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,23 @@ public void testOfType() {
5858
assertEquals(Foo.class, ki.getAnnotationType());
5959
}
6060

61+
public void testWithAnnotation() {
62+
Key<Object> k = Key.get(Object.class);
63+
Key<Object> kf = k.withAnnotation(Foo.class);
64+
assertNull(k.getAnnotationType());
65+
assertEquals(Foo.class, kf.getAnnotationType());
66+
}
67+
68+
public void testWithAnnotationInstance() throws NoSuchFieldException {
69+
Foo annotation = getClass().getDeclaredField("baz").getAnnotation(Foo.class);
70+
Key<Object> k = Key.get(Object.class);
71+
Key<Object> kf = k.withAnnotation(annotation);
72+
assertNull(k.getAnnotationType());
73+
assertNull(k.getAnnotation());
74+
assertEquals(Foo.class, kf.getAnnotationType());
75+
assertEquals(annotation, kf.getAnnotation());
76+
}
77+
6178
public void testKeyEquality() {
6279
Key<List<String>> a = new Key<List<String>>(Foo.class) {};
6380
Key<List<String>> b = Key.get(new TypeLiteral<List<String>>() {}, Foo.class);

0 commit comments

Comments
 (0)