diff --git a/core/src/com/google/inject/Key.java b/core/src/com/google/inject/Key.java index 34628733d7..723ef79659 100644 --- a/core/src/com/google/inject/Key.java +++ b/core/src/com/google/inject/Key.java @@ -290,6 +290,30 @@ public Key ofType(TypeLiteral type) { return new Key(type, annotationStrategy); } + /** + * Returns a new key of the same type with the specified annotation. + * + *

This is equivalent to {@code Key.get(key.getTypeLiteral(), annotation)} but may be more + * convenient to use in certain cases. + * + * @since vNext + */ + public Key withAnnotation(Class annotationType) { + return new Key(typeLiteral, strategyFor(annotationType)); + } + + /** + * Returns a new key of the same type with the specified annotation. + * + *

This is equivalent to {@code Key.get(key.getTypeLiteral(), annotation)} but may be more + * convenient to use in certain cases. + * + * @since vNext + */ + public Key withAnnotation(Annotation annotation) { + return new Key(typeLiteral, strategyFor(annotation)); + } + /** * Returns true if this key has annotation attributes. * diff --git a/core/test/com/google/inject/KeyTest.java b/core/test/com/google/inject/KeyTest.java index 8f5e629230..9806331bab 100644 --- a/core/test/com/google/inject/KeyTest.java +++ b/core/test/com/google/inject/KeyTest.java @@ -58,6 +58,23 @@ public void testOfType() { assertEquals(Foo.class, ki.getAnnotationType()); } + public void testWithAnnotation() { + Key k = Key.get(Object.class); + Key kf = k.withAnnotation(Foo.class); + assertNull(k.getAnnotationType()); + assertEquals(Foo.class, kf.getAnnotationType()); + } + + public void testWithAnnotationInstance() throws NoSuchFieldException { + Foo annotation = getClass().getDeclaredField("baz").getAnnotation(Foo.class); + Key k = Key.get(Object.class); + Key kf = k.withAnnotation(annotation); + assertNull(k.getAnnotationType()); + assertNull(k.getAnnotation()); + assertEquals(Foo.class, kf.getAnnotationType()); + assertEquals(annotation, kf.getAnnotation()); + } + public void testKeyEquality() { Key> a = new Key>(Foo.class) {}; Key> b = Key.get(new TypeLiteral>() {}, Foo.class);