de.fhg.iais.asc.sipmaker.SipMakerDynamicClass.java Source code

Java tutorial

Introduction

Here is the source code for de.fhg.iais.asc.sipmaker.SipMakerDynamicClass.java

Source

package de.fhg.iais.asc.sipmaker;

/******************************************************************************
 * Copyright 2011 (c) Fraunhofer IAIS Netmedia  http://www.iais.fraunhofer.de *
 * ************************************************************************** *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may    *
 * not use this file except in compliance with the License.                   *
 * You may obtain a copy of the License at                                    *
 * http://www.apache.org/licenses/LICENSE-2.0                                 *
 * Unless required by applicable law or agreed to in writing,                 *
 * software distributed under the License is distributed on an "AS IS" BASIS, *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *
 * See the License for the specific language governing permissions and        *
 * limitations under the License.                                             *
 ******************************************************************************/

import org.apache.commons.lang.StringUtils;

import com.google.inject.Injector;

import de.fhg.iais.commons.dbc.DbcException;

public enum SipMakerDynamicClass {
    ;

    // TODO HHILL phase out
    public static Object resolve(final Injector injector, final String packageName, final String className) {
        return resolve(injector, fullClassName(packageName, className), Object.class);
    }

    public static String fullClassName(final String packageName, final String className) {
        StringBuilder fullName = new StringBuilder(120); // pre-set of guessed size reduces expandCapacity() and increases performance

        final String trimedPackageName = StringUtils.trimToNull(packageName);
        if (trimedPackageName != null) {
            fullName.append(trimedPackageName);
            if (!trimedPackageName.endsWith(".")) {
                fullName.append(".");
            }
        }
        fullName.append(StringUtils.trimToEmpty(className));

        return fullName.toString();
    }

    public static <C> C resolve(final Injector injector, final String fullName, final Class<C> clazz) {
        try {
            Class<? extends C> c = Class.forName(fullName).asSubclass(clazz);
            return injector.getInstance(c);
        } catch (ClassNotFoundException e) {
            throw new DbcException("Class \"" + fullName + "\" not found", e);
        }
    }
}