01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */
17: package org.apache.commons.discovery.tools;
18:
19: import org.apache.commons.discovery.ResourceClass;
20: import org.apache.commons.discovery.ResourceClassIterator;
21: import org.apache.commons.discovery.resource.classes.DiscoverClasses;
22: import org.apache.commons.discovery.resource.ClassLoaders;
23:
24: /**
25: * Holder for a default class.
26: *
27: * Class may be specified by name (String) or class (Class).
28: * Using the holder complicates the users job, but minimized # of API's.
29: *
30: * @author Richard A. Sitze
31: */
32: public class DefaultClassHolder {
33: private Class defaultClass;
34: private final String defaultName;
35:
36: public DefaultClassHolder(Class defaultClass) {
37: this .defaultClass = defaultClass;
38: this .defaultName = defaultClass.getName();
39: }
40:
41: public DefaultClassHolder(String defaultName) {
42: this .defaultClass = null;
43: this .defaultName = defaultName;
44: }
45:
46: /**
47: * @param spi non-null SPI
48: * @param loaders Used only if class needs to be loaded.
49: *
50: * @return Default Class. Load the class if necessary,
51: * and verify that it implements the SPI.
52: * (this forces the check, no way out..).
53: */
54: public Class getDefaultClass(SPInterface spi, ClassLoaders loaders) {
55: if (defaultClass == null) {
56: DiscoverClasses classDiscovery = new DiscoverClasses(
57: loaders);
58: ResourceClassIterator classes = classDiscovery
59: .findResourceClasses(getDefaultName());
60: if (classes.hasNext()) {
61: ResourceClass info = classes.nextResourceClass();
62: try {
63: defaultClass = info.loadClass();
64: } catch (Exception e) {
65: // ignore
66: }
67: }
68: }
69:
70: if (defaultClass != null) {
71: spi.verifyAncestory(defaultClass);
72: }
73:
74: return defaultClass;
75: }
76:
77: public String getDefaultName() {
78: return defaultName;
79: }
80: }
|