Skip to content

Commit

Permalink
Add a .withAnnotation() method to simplify creating keys with differe…
Browse files Browse the repository at this point in the history
…nt annotations.

Closes #1108

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=313246519
  • Loading branch information
kashike authored and kevinb9n committed May 27, 2020
1 parent c83404b commit d071802
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
24 changes: 24 additions & 0 deletions core/src/com/google/inject/Key.java
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,30 @@ public <T> Key<T> ofType(TypeLiteral<T> type) {
return new Key<T>(type, annotationStrategy);
}

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

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

/**
* Returns true if this key has annotation attributes.
*
Expand Down
17 changes: 17 additions & 0 deletions core/test/com/google/inject/KeyTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,23 @@ public void testOfType() {
assertEquals(Foo.class, ki.getAnnotationType());
}

public void testWithAnnotation() {
Key<Object> k = Key.get(Object.class);
Key<Object> 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<Object> k = Key.get(Object.class);
Key<Object> kf = k.withAnnotation(annotation);
assertNull(k.getAnnotationType());
assertNull(k.getAnnotation());
assertEquals(Foo.class, kf.getAnnotationType());
assertEquals(annotation, kf.getAnnotation());
}

public void testKeyEquality() {
Key<List<String>> a = new Key<List<String>>(Foo.class) {};
Key<List<String>> b = Key.get(new TypeLiteral<List<String>>() {}, Foo.class);
Expand Down

0 comments on commit d071802

Please sign in to comment.