2 * Copyright 2007 the original author or authors.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.wamblee.system;
18 import java.util.Arrays;
20 public class DefaultRequiredInterface implements RequiredInterface {
23 private Class[] _required;
24 private ProvidedInterface _provider;
26 public DefaultRequiredInterface(String aName, Class aInterface) {
27 this(aName, new Class[] { aInterface });
30 public DefaultRequiredInterface(String aName, Class[] aInterfaces) {
32 _required = aInterfaces;
36 public String getName() {
41 public boolean implementedBy(ProvidedInterface aDescriptor) {
42 Class[] provided = aDescriptor.getInterfaceTypes();
43 for (Class required : _required) {
44 if ( !serviceProvided(required, provided)) {
48 // all required interfaces are provided.
53 * Check if the required interface is implemented by one of the provided interfaces.
54 * @param aRequired required interface
55 * @param aProvided Provided interfaces.
58 private boolean serviceProvided(Class aRequired, Class[] aProvided) {
59 for (Class provided: aProvided) {
61 provided.asSubclass(aRequired);
63 } catch (ClassCastException e) {
64 // No match, try the next one.
71 public ProvidedInterface getProvider() {
76 public void setProvider(ProvidedInterface aProvider) {
77 _provider = aProvider;
81 public <T> T getImplementation(Class<T> aClass) {
82 if ( _provider == null ) {
85 return (T)_provider.getImplementation();
89 public boolean equals(Object obj) {
90 if ( !(obj instanceof DefaultRequiredInterface)) {
93 DefaultRequiredInterface descr = (DefaultRequiredInterface)obj;
94 if ( _required.length != descr._required.length ) {
97 String[] interfaces1 = new String[_required.length];
98 String[] interfaces2 = new String[_required.length];
99 for (int i = 0; i < _required.length; i++) {
100 interfaces1[i] = _required[i].getName();
101 interfaces2[i] = descr._required[i].getName();
103 Arrays.sort(interfaces1);
104 Arrays.sort(interfaces2);
105 return Arrays.equals(interfaces1, interfaces2);
109 public int hashCode() {
110 return _required.hashCode();
114 public String toString() {
115 StringBuffer buf = new StringBuffer();
116 for (Class intf: _required) {
117 buf.append("." + intf.getName());
119 return buf.toString();