1 /*
2  * Copyright 2016-17, OpenCensus Authors
3  *
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 
17 package io.opencensus.internal;
18 
19 import java.util.ServiceConfigurationError;
20 
21 /**
22  * OpenCensus service provider mechanism.
23  *
24  * <pre>{@code
25  * // Initialize a variable using reflection.
26  * foo = Provider.createInstance(
27  *     Class.forName("FooImpl", true, classLoader), Foo.class);
28  * }</pre>
29  */
30 public final class Provider {
Provider()31   private Provider() {}
32 
33   /**
34    * Tries to create an instance of the given rawClass as a subclass of the given superclass.
35    *
36    * @param rawClass The class that is initialized.
37    * @param superclass The initialized class must be a subclass of this.
38    * @return an instance of the class given rawClass which is a subclass of the given superclass.
39    * @throws ServiceConfigurationError if any error happens.
40    */
createInstance(Class<?> rawClass, Class<T> superclass)41   public static <T> T createInstance(Class<?> rawClass, Class<T> superclass) {
42     try {
43       return rawClass.asSubclass(superclass).getConstructor().newInstance();
44     } catch (Exception e) {
45       throw new ServiceConfigurationError(
46           "Provider " + rawClass.getName() + " could not be instantiated.", e);
47     }
48   }
49 }
50