下面列出了怎么用com.google.common.collect.ImmutableClassToInstanceMap的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
@Before
public void setUp() throws Exception {
super.setUp();
doReturn(this.ribSupport).when(this.extension).getRIBSupport(any(TablesKey.class));
final NodeIdentifier nii = new NodeIdentifier(QName.create("", "test").intern());
doReturn(nii).when(this.ribSupport).routeAttributesIdentifier();
doReturn(ImmutableSet.of()).when(this.ribSupport).cacheableAttributeObjects();
final MapEntryNode emptyTable = mock(MapEntryNode.class);
doReturn(emptyTable).when(this.ribSupport).emptyTable();
final NodeIdentifierWithPredicates niie = NodeIdentifierWithPredicates.of(Rib.QNAME,
QName.create("", "test").intern(), "t");
doReturn(niie).when(emptyTable).getIdentifier();
doReturn(QName.create("", "test").intern()).when(emptyTable).getNodeType();
doReturn(this.domTx).when(this.domDataBroker).createMergingTransactionChain(any());
final DOMDataTreeChangeService dOMDataTreeChangeService = mock(DOMDataTreeChangeService.class);
doReturn(ImmutableClassToInstanceMap.of(DOMDataTreeChangeService.class, dOMDataTreeChangeService))
.when(this.domDataBroker).getExtensions();
doReturn(mock(ListenerRegistration.class)).when(dOMDataTreeChangeService)
.registerDataTreeChangeListener(any(), any());
doNothing().when(this.serviceRegistration).unregister();
}
@Override
public <T extends PeerConstraint> boolean addPeerConstraint(final Class<T> classType, final T peerConstraint) {
requireNonNull(classType);
requireNonNull(peerConstraint);
ImmutableClassToInstanceMap<PeerConstraint> local = constraints;
while (!local.containsKey(classType)) {
final Builder<PeerConstraint> builder = ImmutableClassToInstanceMap.builder();
builder.putAll(local);
builder.put(classType, peerConstraint);
if (CONSTRAINTS_UPDATER.compareAndSet(this, local, builder.build())) {
// Successfully updated, finished
return true;
}
// Raced with another update, retry
local = constraints;
}
return false;
}
@SuppressWarnings("unchecked")
public static ImmutableClassToInstanceMap<Annotation> annotationMap(Symbol symbol) {
ImmutableClassToInstanceMap.Builder<Annotation> builder = ImmutableClassToInstanceMap.builder();
for (Compound compound : symbol.getAnnotationMirrors()) {
Name qualifiedAnnotationType =
((TypeElement) compound.getAnnotationType().asElement()).getQualifiedName();
try {
Class<? extends Annotation> annotationClazz =
Class.forName(qualifiedAnnotationType.toString()).asSubclass(Annotation.class);
builder.put((Class) annotationClazz,
AnnotationProxyMaker.generateAnnotation(compound, annotationClazz));
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Unrecognized annotation type", e);
}
}
return builder.build();
}
public static RefasterRule<?, ?> create(String qualifiedTemplateClass,
Collection<? extends Template<?>> beforeTemplates, @Nullable Template<?> afterTemplate,
ImmutableClassToInstanceMap<Annotation> annotations) {
checkState(!beforeTemplates.isEmpty(),
"No @BeforeTemplate was found in the specified class: %s", qualifiedTemplateClass);
Class<?> templateType = beforeTemplates.iterator().next().getClass();
for (Template<?> beforeTemplate : beforeTemplates) {
checkState(beforeTemplate.getClass().equals(templateType),
"Expected all templates to be of type %s but found template of type %s in %s",
templateType, beforeTemplate.getClass(), qualifiedTemplateClass);
}
if (afterTemplate != null) {
checkState(afterTemplate.getClass().equals(templateType),
"Expected all templates to be of type %s but found template of type %s in %s",
templateType, afterTemplate.getClass(), qualifiedTemplateClass);
}
@SuppressWarnings("unchecked")
RefasterRule<?, ?> result = new AutoValue_RefasterRule(
qualifiedTemplateClass, ImmutableList.copyOf(beforeTemplates), afterTemplate, annotations);
return result;
}
@Test
public void genericTemplate() {
compile(
"import java.util.List;",
"class GenericTemplateExample {",
" public <E> E example(List<E> list) {",
" return list.get(0);",
" }",
"}");
assertEquals(
ExpressionTemplate.create(
ImmutableClassToInstanceMap.<Annotation>builder().build(),
ImmutableList.of(UTypeVar.create("E")),
ImmutableMap.of("list", UClassType.create("java.util.List", UTypeVar.create("E"))),
UMethodInvocation.create(
UMemberSelect.create(
UFreeIdent.create("list"),
"get",
UMethodType.create(UTypeVar.create("E"), UPrimitiveType.INT)),
ULiteral.intLit(0)),
UTypeVar.create("E")),
UTemplater.createTemplate(context, getMethodDeclaration("example")));
}
@Test
public void recursiveTypes() {
compile(
"class RecursiveTypeExample {",
" public <E extends Enum<E>> E example(E e) {",
" return e;",
" }",
"}");
Template<?> template = UTemplater.createTemplate(context, getMethodDeclaration("example"));
UTypeVar eVar = Iterables.getOnlyElement(template.typeVariables());
assertEquals(
ExpressionTemplate.create(
ImmutableClassToInstanceMap.<Annotation>builder().build(),
ImmutableList.of(UTypeVar.create("E", UClassType.create("java.lang.Enum", eVar))),
ImmutableMap.of("e", eVar),
UFreeIdent.create("e"),
eVar),
template);
}
private static ClassToInstanceMap<Context> getContextMap(UUID actionUUID, Player player, VirtualChestHandheldItem itemTemplate)
{
ImmutableClassToInstanceMap.Builder<Context> contextBuilder = ImmutableClassToInstanceMap.builder();
contextBuilder.put(Context.HANDHELD_ITEM, new HandheldItemContext(itemTemplate::matchItem));
contextBuilder.put(Context.ACTION_UUID, new ActionUUIDContext(actionUUID));
contextBuilder.put(Context.PLAYER, new PlayerContext(player));
return contextBuilder.build();
}
@SuppressWarnings("unchecked")
private void mockedMethods() throws Exception {
MockitoAnnotations.initMocks(this);
final ReadTransaction readTx = mock(ReadTransaction.class);
doReturn(new TestListenerRegistration()).when(this.service)
.registerDataTreeChangeListener(any(DOMDataTreeIdentifier.class),
any(ClusteredDOMDataTreeChangeListener.class));
doNothing().when(readTx).close();
doNothing().when(this.domTransWrite).put(eq(LogicalDatastoreType.OPERATIONAL),
any(YangInstanceIdentifier.class), any(NormalizedNode.class));
doNothing().when(this.domTransWrite).delete(eq(LogicalDatastoreType.OPERATIONAL),
any(YangInstanceIdentifier.class));
doNothing().when(this.domTransWrite).merge(eq(LogicalDatastoreType.OPERATIONAL),
any(YangInstanceIdentifier.class), any(NormalizedNode.class));
doReturn(FluentFutures.immediateFluentFuture(Optional.empty())).when(readTx)
.read(eq(LogicalDatastoreType.OPERATIONAL), any(InstanceIdentifier.class));
doNothing().when(this.domChain).close();
doReturn(this.domTransWrite).when(this.domChain).newWriteOnlyTransaction();
doNothing().when(getTransaction()).put(eq(LogicalDatastoreType.OPERATIONAL),
eq(YangInstanceIdentifier.of(BgpRib.QNAME)), any(NormalizedNode.class));
doReturn(ImmutableClassToInstanceMap.of(DOMDataTreeChangeService.class, this.service)).when(this.dom)
.getExtensions();
doReturn(this.domChain).when(this.dom).createMergingTransactionChain(any(AbstractPeer.class));
doReturn(this.transWrite).when(this.chain).newWriteOnlyTransaction();
doReturn(Optional.empty()).when(this.future).get();
doReturn(this.future).when(this.domTransWrite).commit();
doNothing().when(this.future).addListener(any(Runnable.class), any(Executor.class));
doNothing().when(this.transWrite).mergeParentStructurePut(eq(LogicalDatastoreType.OPERATIONAL),
any(InstanceIdentifier.class), any(DataObject.class));
doNothing().when(this.transWrite).put(eq(LogicalDatastoreType.OPERATIONAL),
any(InstanceIdentifier.class), any(DataObject.class));
doReturn(this.future).when(this.transWrite).commit();
}
public static BlockTemplate create(
Iterable<UTypeVar> typeVariables,
Map<String, ? extends UType> expressionArgumentTypes,
UStatement... templateStatements) {
return create(
ImmutableClassToInstanceMap.<Annotation>builder().build(),
typeVariables, expressionArgumentTypes, ImmutableList.copyOf(templateStatements));
}
public static BlockTemplate create(
ImmutableClassToInstanceMap<Annotation> annotations,
Iterable<UTypeVar> typeVariables,
Map<String, ? extends UType> expressionArgumentTypes,
Iterable<? extends UStatement> templateStatements) {
return new AutoValue_BlockTemplate(
annotations,
ImmutableList.copyOf(typeVariables),
ImmutableMap.copyOf(expressionArgumentTypes),
ImmutableList.copyOf(templateStatements));
}
@SuppressWarnings("unchecked")
@Override
public ImmutableClassToInstanceMap<Annotation> annotations() {
ImmutableClassToInstanceMap.Builder<Annotation> builder = ImmutableClassToInstanceMap.builder();
for (Annotation annotation : checker().getClass().getDeclaredAnnotations()) {
builder.put((Class) annotation.annotationType(), annotation);
}
return builder.build();
}
public static ExpressionTemplate create(
Map<String, ? extends UType> expressionArgumentTypes,
UExpression expression, UType returnType) {
return create(
ImmutableClassToInstanceMap.<Annotation>builder().build(),
ImmutableList.<UTypeVar>of(),
expressionArgumentTypes,
expression,
returnType);
}
public static ExpressionTemplate create(
ImmutableClassToInstanceMap<Annotation> annotations,
Iterable<UTypeVar> typeVariables,
Map<String, ? extends UType> expressionArgumentTypes,
UExpression expression, UType returnType) {
return new AutoValue_ExpressionTemplate(
annotations,
ImmutableList.copyOf(typeVariables),
ImmutableMap.copyOf(expressionArgumentTypes),
expression,
returnType);
}
@Test
public void genericMethodInvocation() {
compile(
"import java.util.Collections;",
"import java.util.List;",
"class GenericTemplateExample {",
" public <E> List<E> example(List<E> list) {",
" return Collections.unmodifiableList(list);",
" }",
"}");
UTypeVar tVar = UTypeVar.create("T");
UTypeVar eVar = UTypeVar.create("E");
assertEquals(
ExpressionTemplate.create(
ImmutableClassToInstanceMap.<Annotation>builder().build(),
ImmutableList.of(eVar),
ImmutableMap.of("list", UClassType.create("java.util.List", eVar)),
UMethodInvocation.create(
UStaticIdent.create(
"java.util.Collections",
"unmodifiableList",
UForAll.create(
ImmutableList.of(tVar),
UMethodType.create(
UClassType.create("java.util.List", tVar),
UClassType.create(
"java.util.List",
UWildcardType.create(BoundKind.EXTENDS, tVar))))),
UFreeIdent.create("list")),
UClassType.create("java.util.List", eVar)),
UTemplater.createTemplate(context, getMethodDeclaration("example")));
}
@Test
public void recursiveType() {
/*
* Template:
* <E extends Enum<E>> String example(E e) {
* return e.name();
* }
*/
UTypeVar eTypeVar = UTypeVar.create("E");
eTypeVar.setUpperBound(UClassType.create("java.lang.Enum", eTypeVar));
ExpressionTemplate template = ExpressionTemplate.create(
ImmutableClassToInstanceMap.<Annotation>builder().build(),
ImmutableList.of(eTypeVar),
ImmutableMap.of("value", eTypeVar),
UMethodInvocation.create(
UMemberSelect.create(UFreeIdent.create("value"), "name",
UMethodType.create(UClassType.create("java.lang.String")))),
UClassType.create("java.lang.String"));
compile(
"import java.math.RoundingMode;",
"class RecursiveTypeExample {",
" public void example() {",
" System.out.println(RoundingMode.FLOOR.name());",
" }",
"}");
expectMatches(template,
Match.create(ImmutableMap.of(
"value", "RoundingMode.FLOOR",
"E", "java.math.RoundingMode")));
}
/** Constructs the registry configured by this builder. */
public ModuleActionContextRegistry build() throws AbruptExitException {
HashSet<Class<?>> usedTypes = new HashSet<>();
MutableClassToInstanceMap<ActionContext> contextToInstance =
MutableClassToInstanceMap.create();
for (ActionContextInformation<?> actionContextInformation : actionContexts) {
Class<? extends ActionContext> identifyingType = actionContextInformation.identifyingType();
if (typeToRestriction.containsKey(identifyingType)) {
String restriction = typeToRestriction.get(identifyingType);
if (!actionContextInformation.commandLineIdentifiers().contains(restriction)
&& !restriction.isEmpty()) {
continue;
}
}
usedTypes.add(identifyingType);
actionContextInformation.addToMap(contextToInstance);
}
Sets.SetView<Class<?>> unusedRestrictions =
Sets.difference(typeToRestriction.keySet(), usedTypes);
if (!unusedRestrictions.isEmpty()) {
throw new AbruptExitException(
DetailedExitCode.of(
FailureDetail.newBuilder()
.setMessage(getMissingIdentifierErrorMessage(unusedRestrictions).toString())
.setExecutionOptions(
FailureDetails.ExecutionOptions.newBuilder()
.setCode(Code.RESTRICTION_UNMATCHED_TO_ACTION_CONTEXT))
.build()));
}
return new ModuleActionContextRegistry(ImmutableClassToInstanceMap.copyOf(contextToInstance));
}
private FakeSpawnExecutionContext getSpawnContext(Spawn spawn) {
AbstractSpawnStrategy fakeLocalStrategy = new AbstractSpawnStrategy(execRoot, localRunner) {};
ClassToInstanceMap<ActionContext> actionContextRegistry =
ImmutableClassToInstanceMap.of(RemoteLocalFallbackRegistry.class, () -> fakeLocalStrategy);
return new FakeSpawnExecutionContext(
spawn, fakeFileCache, execRoot, outErr, actionContextRegistry);
}
@Test
public void whenBuilderUser_thenCreateMap() {
ClassToInstanceMap<Action> map = ImmutableClassToInstanceMap.<Action>builder()
.put(Save.class, new Save())
.put(Open.class, new Open())
.build();
assertEquals(2, map.size());
}
@Test
public void givenClassToInstanceMap_whenGetCalled_returnUpperBoundElement() {
ClassToInstanceMap<Action> map = ImmutableClassToInstanceMap.of(Save.class, new Save());
Action action = map.get(Save.class);
assertTrue(action instanceof Save);
// Use getInstance to avoid casting
Save save = map.getInstance(Save.class);
}
PluginRegistry() {
this(ImmutableClassToInstanceMap.of());
}
@Override
@Before
public void setUp() throws Exception {
super.setUp();
final List<OptionalCapabilities> capa = new ArrayList<>();
capa.add(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder()
.addAugmentation(new CParameters1Builder()
.setMultiprotocolCapability(new MultiprotocolCapabilityBuilder()
.setAfi(this.ipv4tt.getAfi()).setSafi(this.ipv4tt.getSafi()).build())
.setGracefulRestartCapability(new GracefulRestartCapabilityBuilder().setRestartTime(Uint16.ZERO)
.build()).build())
.setAs4BytesCapability(new As4BytesCapabilityBuilder().setAsNumber(AS_NUMBER).build()).build())
.build());
capa.add(new OptionalCapabilitiesBuilder()
.setCParameters(BgpExtendedMessageUtil.EXTENDED_MESSAGE_CAPABILITY).build());
this.classicOpen = new OpenBuilder()
.setMyAsNumber(Uint16.valueOf(AS_NUMBER.getValue()))
.setHoldTimer(Uint16.valueOf(HOLD_TIMER))
.setVersion(new ProtocolVersion(Uint8.valueOf(4)))
.setBgpParameters(List.of(new BgpParametersBuilder()
.setOptionalCapabilities(capa)
.build()))
.setBgpIdentifier(BGP_ID)
.build();
doReturn(null).when(mock(ChannelFuture.class)).addListener(any());
doReturn(this.eventLoop).when(this.speakerListener).eventLoop();
doReturn(true).when(this.speakerListener).isActive();
doAnswer(invocation -> {
final Runnable command = invocation.getArgument(0);
final long delay = (long) invocation.getArgument(1);
final TimeUnit unit = invocation.getArgument(2);
GlobalEventExecutor.INSTANCE.schedule(command, delay, unit);
return null;
}).when(this.eventLoop).schedule(any(Runnable.class), any(long.class), any(TimeUnit.class));
doReturn("TestingChannel").when(this.speakerListener).toString();
doReturn(true).when(this.speakerListener).isWritable();
doReturn(new InetSocketAddress(InetAddress.getByName(BGP_ID.getValue()), 179))
.when(this.speakerListener).remoteAddress();
doReturn(new InetSocketAddress(InetAddress.getByName(LOCAL_IP), LOCAL_PORT))
.when(this.speakerListener).localAddress();
doReturn(this.pipeline).when(this.speakerListener).pipeline();
doReturn(this.pipeline).when(this.pipeline).replace(any(ChannelHandler.class),
any(String.class),
any(ChannelHandler.class));
doReturn(null).when(this.pipeline).replace(ArgumentMatchers.<Class<ChannelHandler>>any(),
any(String.class),
any(ChannelHandler.class));
doReturn(this.pipeline).when(this.pipeline).addLast(any(ChannelHandler.class));
final ChannelFuture futureChannel = mock(ChannelFuture.class);
doReturn(null).when(futureChannel).addListener(any());
doReturn(futureChannel).when(this.speakerListener).close();
doReturn(futureChannel).when(this.speakerListener).writeAndFlush(any(Notify.class));
doReturn(this.domChain).when(this.domBroker).createMergingTransactionChain(any());
doReturn(this.tx).when(this.domChain).newWriteOnlyTransaction();
final DOMDataTreeChangeService dOMDataTreeChangeService = mock(DOMDataTreeChangeService.class);
final ListenerRegistration<?> listener = mock(ListenerRegistration.class);
doReturn(listener).when(dOMDataTreeChangeService).registerDataTreeChangeListener(any(), any());
doNothing().when(listener).close();
doNothing().when(this.domChain).close();
doReturn(ImmutableClassToInstanceMap.of(DOMDataTreeChangeService.class, dOMDataTreeChangeService))
.when(this.domBroker).getExtensions();
doNothing().when(this.tx).merge(eq(LogicalDatastoreType.OPERATIONAL),
any(YangInstanceIdentifier.class), any(NormalizedNode.class));
doNothing().when(this.tx).put(eq(LogicalDatastoreType.OPERATIONAL),
any(YangInstanceIdentifier.class), any(NormalizedNode.class));
doNothing().when(this.tx).delete(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class));
doReturn(CommitInfo.emptyFluentFuture()).when(this.tx).commit();
}
@Override
public ClassToInstanceMap<NormalizedNodeStreamWriterExtension> getExtensions() {
return ImmutableClassToInstanceMap.of(StreamWriterMountPointExtension.class, this);
}
@Override
public final ClassToInstanceMap<NormalizedNodeStreamWriterExtension> getExtensions() {
return ImmutableClassToInstanceMap.of(StreamWriterMetadataExtension.class, this);
}
@Override
public final ClassToInstanceMap<NormalizedNodeStreamWriterExtension> getExtensions() {
return ImmutableClassToInstanceMap.of(StreamWriterMountPointExtension.class, this);
}
@Override
public final ClassToInstanceMap<NormalizedNodeStreamWriterExtension> getExtensions() {
return ImmutableClassToInstanceMap.of(StreamWriterMetadataExtension.class, this);
}
public HwvtepTableReader(final HwvtepConnectionInstance connectionInstance) {
this.connectionInstance = connectionInstance;
TypedDatabaseSchema dbSchema = null;
try {
dbSchema = connectionInstance.getSchema(HwvtepSchemaConstants.HARDWARE_VTEP).get();
} catch (InterruptedException | ExecutionException e) {
LOG.warn("Not able to fetch schema for database {} from device {}",
HwvtepSchemaConstants.HARDWARE_VTEP, connectionInstance.getConnectionInfo(), e);
}
final Builder<TypedBaseTable<?>> tableBuilder = ImmutableClassToInstanceMap.<TypedBaseTable<?>>builder();
final ImmutableMap.Builder<Class<? extends Identifiable<?>>, WhereClauseGetter<?>> whereBuilder =
ImmutableMap.builderWithExpectedSize(4);
if (dbSchema != null) {
final McastMacsRemote mcastMacsTable = dbSchema.getTypedRowWrapper(McastMacsRemote.class, null);
if (mcastMacsTable != null) {
tableBuilder.put(McastMacsRemote.class, mcastMacsTable);
whereBuilder.put(RemoteMcastMacs.class, new RemoteMcastMacWhereClauseGetter(mcastMacsTable));
}
final UcastMacsRemote ucastMacsTable = dbSchema.getTypedRowWrapper(UcastMacsRemote.class, null);
if (ucastMacsTable != null) {
tableBuilder.put(UcastMacsRemote.class, ucastMacsTable);
whereBuilder.put(RemoteUcastMacs.class, new RemoteUcastMacWhereClauseGetter(ucastMacsTable));
}
final LogicalSwitch lsTable = dbSchema.getTypedRowWrapper(LogicalSwitch.class, null);
if (lsTable != null) {
tableBuilder.put(LogicalSwitch.class, lsTable);
whereBuilder.put(LogicalSwitches.class, new LogicalSwitchWhereClauseGetter(lsTable));
}
final PhysicalLocator plTable = dbSchema.getTypedRowWrapper(PhysicalLocator.class, null);
if (plTable != null) {
tableBuilder.put(PhysicalLocator.class, plTable);
whereBuilder.put(TerminationPoint.class, new LocatorWhereClauseGetter(plTable));
}
final PhysicalPort physicalPort = dbSchema.getTypedRowWrapper(PhysicalPort.class, null);
if (physicalPort != null) {
tableBuilder.put(PhysicalPort.class, physicalPort);
}
}
tables = tableBuilder.build();
whereClauseGetters = whereBuilder.build();
}
/**
* Returns a template based on a method. One-line methods starting with a {@code return} statement
* are guessed to be expression templates, and all other methods are guessed to be block
* templates.
*/
public static Template<?> createTemplate(Context context, MethodTree decl) {
MethodSymbol declSym = ASTHelpers.getSymbol(decl);
ImmutableClassToInstanceMap<Annotation> annotations = UTemplater.annotationMap(declSym);
ImmutableMap<String, VarSymbol> freeExpressionVars = freeExpressionVariables(decl);
Context subContext = new SubContext(context);
if (annotations.containsKey(AlsoReverseTernary.class)) {
subContext.put(AlsoReverseTernary.class, annotations.getInstance(AlsoReverseTernary.class));
}
final UTemplater templater = new UTemplater(freeExpressionVars, subContext);
ImmutableMap<String, UType> expressionVarTypes = ImmutableMap.copyOf(
Maps.transformValues(freeExpressionVars, new Function<VarSymbol, UType>() {
@Override
public UType apply(VarSymbol sym) {
return templater.template(sym.type);
}
}));
UType genericType = templater.template(declSym.type);
List<UTypeVar> typeParameters;
UMethodType methodType;
if (genericType instanceof UForAll) {
UForAll forAllType = (UForAll) genericType;
typeParameters = forAllType.getTypeVars();
methodType = (UMethodType) forAllType.getQuantifiedType();
} else if (genericType instanceof UMethodType) {
typeParameters = ImmutableList.of();
methodType = (UMethodType) genericType;
} else {
throw new IllegalArgumentException(
"Expected genericType to be either a ForAll or a UMethodType, but was " + genericType);
}
List<? extends StatementTree> bodyStatements = decl.getBody().getStatements();
if (bodyStatements.size() == 1
&& Iterables.getOnlyElement(bodyStatements).getKind() == Kind.RETURN
&& context.get(REQUIRE_BLOCK_KEY) == null) {
ExpressionTree expression =
((ReturnTree) Iterables.getOnlyElement(bodyStatements)).getExpression();
return ExpressionTemplate.create(
annotations, typeParameters, expressionVarTypes,
templater.template(expression), methodType.getReturnType());
} else {
List<UStatement> templateStatements = new ArrayList<>();
for (StatementTree statement : bodyStatements) {
templateStatements.add(templater.template(statement));
}
return BlockTemplate.create(annotations,
typeParameters, expressionVarTypes, templateStatements);
}
}
public static RefasterRule<?, ?> create(String qualifiedTemplateClass,
Collection<? extends Template<?>> beforeTemplates, @Nullable Template<?> afterTemplate) {
return create(qualifiedTemplateClass, beforeTemplates, afterTemplate,
ImmutableClassToInstanceMap.<Annotation>builder().build());
}
@Override
public abstract ImmutableClassToInstanceMap<Annotation> annotations();
@Test
public void returnTypeMatters() {
/* Template:
* <E> List<E> template(List<E> list) {
* return Collections.unmodifiableList(list);
* }
*
* Note that Collections.unmodifiableList takes a List<? extends T>,
* but we're restricting to the case where the return type is the same.
*/
UTypeVar tVar = UTypeVar.create("T");
UTypeVar eVar = UTypeVar.create("E");
ExpressionTemplate template = ExpressionTemplate.create(
ImmutableClassToInstanceMap.<Annotation>builder().build(),
ImmutableList.of(eVar),
ImmutableMap.of("list", UClassType.create("java.util.List", eVar)),
UMethodInvocation.create(
UStaticIdent.create("java.util.Collections", "unmodifiableList",
UForAll.create(ImmutableList.of(tVar),
UMethodType.create(
UClassType.create("java.util.List", tVar),
UClassType.create("java.util.List",
UWildcardType.create(BoundKind.EXTENDS, tVar))))),
UFreeIdent.create("list")),
UClassType.create("java.util.List", eVar));
compile(
"import java.util.ArrayList;",
"import java.util.Collections;",
"import java.util.List;",
"class ReturnTypeMattersExample {",
" public void example() {",
// positive examples
" Collections.unmodifiableList(new ArrayList<String>());",
" List<Integer> ints = Collections.unmodifiableList(Collections.singletonList(1));",
// negative examples
" List<CharSequence> seqs = Collections.<CharSequence>unmodifiableList(",
" new ArrayList<String>());",
" }",
"}");
expectMatches(template,
Match.create(ImmutableMap.of(
"list", "new ArrayList<String>()",
"E", "java.lang.String")),
Match.create(ImmutableMap.of(
"list", "Collections.singletonList(1)",
"E", "java.lang.Integer")));
}