1 // Copyright 2012 Google Inc. All rights reserved.
3 package com
.google
.appengine
.spi
;
5 import com
.google
.common
.base
.Objects
;
6 import com
.google
.common
.primitives
.Ints
;
9 * A base class for service factory creation that can be registered with the ProviderRegistry.
11 * @param <I> is the interface the provided factory must implement.
13 public abstract class FactoryProvider
<I
> implements Comparable
<FactoryProvider
<?
>> {
14 private final Class
<I
> baseInterface
;
16 protected FactoryProvider(Class
<I
> baseInterface
) {
17 this.baseInterface
= baseInterface
;
20 protected Class
<I
> getBaseInterface() {
25 * Return an instance of the factory
27 protected abstract I
getFactoryInstance();
29 private int getPrecedence() {
30 ServiceProvider annotation
= getClass().getAnnotation(ServiceProvider
.class);
31 return (annotation
!= null) ? annotation
.precedence() : ServiceProvider
.DEFAULT_PRECEDENCE
;
35 * This ensures that a list of these will be sorted so that higher precedence entries come later
39 public int compareTo(FactoryProvider
<?
> o
) {
41 getBaseInterface().getCanonicalName().compareTo(o
.getBaseInterface().getCanonicalName());
42 return result
!= 0 ? result
: Ints
.compare(getPrecedence(), o
.getPrecedence());
46 public int hashCode() {
47 return Objects
.hashCode(getBaseInterface().getCanonicalName(), getPrecedence());
51 * Included to support sorting by precedence (@see #compareTo(FactoryProvider))
53 @SuppressWarnings("unchecked")
55 public boolean equals(Object o
) {
56 if (o
== null || !(o
instanceof FactoryProvider
)) {
59 return (compareTo((FactoryProvider
<I
>) o
) == 0);