View Javadoc
1   package org.apache.rat.mp.util;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  import org.apache.maven.plugin.MojoExecutionException;
23  import org.apache.maven.plugin.MojoFailureException;
24  
25  public final class ConfigurationHelper {
26  
27      private ConfigurationHelper() {
28          // prevent instantiation
29      }
30  
31      public static <T> T newInstance(final Class<T> clazz, final String className)
32              throws MojoExecutionException, MojoFailureException {
33          try {
34              final ClassLoader cl = Thread.currentThread()
35                      .getContextClassLoader();
36              @SuppressWarnings("unchecked") // incorrect cast will be caught below
37              final T o = (T) cl.loadClass(className).newInstance();
38  
39              if (!clazz.isAssignableFrom(o.getClass())) {
40                  throw new MojoFailureException("The class "
41                          + o.getClass().getName() + " does not implement "
42                          + clazz.getName());
43              }
44              return o;
45          } catch (final InstantiationException e) {
46              throw new MojoExecutionException("Failed to instantiate class "
47                      + className + ": " + e.getMessage(), e);
48          } catch (final ClassCastException e) {
49              throw new MojoExecutionException("The class " + className
50                      + " is not implementing " + clazz.getName() + ": "
51                      + e.getMessage(), e);
52          } catch (final IllegalAccessException e) {
53              throw new MojoExecutionException("Illegal access to class "
54                      + className + ": " + e.getMessage(), e);
55          } catch (final ClassNotFoundException e) {
56              throw new MojoExecutionException("Class " + className
57                      + " not found: " + e.getMessage(), e);
58          }
59      }
60  
61  }