All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.cattleframework.utils.reflect.ClassUtils Maven / Gradle / Ivy

There is a newer version: 1.0.1-M3
Show newest version
/*
 * Copyright (C) 2018 the original author or authors.
 *
 * 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.
 */
package org.cattleframework.utils.reflect;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;

import org.cattleframework.exception.CattleException;
import org.cattleframework.exception.ExceptionWrapUtils;
import org.objenesis.Objenesis;
import org.objenesis.ObjenesisStd;

/**
 * 类的工具
 * 
 * @author orange
 *
 */
public final class ClassUtils {

    private static final String CGLIB_CLASS_SEPARATOR = "$$";

    private static Objenesis objenesis = new ObjenesisStd(true);

    private ClassUtils() {
    }

    public static  T instanceEmpty(Class type) {
	return objenesis.newInstance(type);
    }

    public static Class getUserClass(Class clazz) {
	if (clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) {
	    Class superclass = clazz.getSuperclass();
	    if (superclass != null && superclass != Object.class) {
		return superclass;
	    }
	}
	return clazz;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static  Class getTypeClass(java.lang.reflect.Type type) {
	if (type == null) {
	    return null;
	} else if (type instanceof Class) {
	    return (Class) type;
	} else if (type instanceof ParameterizedType) {
	    return (Class) ((ParameterizedType) type).getRawType();
	} else if (type instanceof TypeVariable) {
	    return getTypeClass(((TypeVariable) type).getBounds()[0]);
	} else if (type instanceof WildcardType) {
	    return getTypeClass(((WildcardType) type).getUpperBounds()[0]);
	}
	throw new CattleException("不能获得java类型的类,从类: " + type);
    }

    public static Class getClass(String className, boolean ignoreException) {
	try {
	    return Class.forName(className);
	} catch (ClassNotFoundException | NoClassDefFoundError e) {
	    if (ignoreException) {
		return null;
	    }
	    throw ExceptionWrapUtils.wrap(e);
	}
    }

    public static Class getClass(String className) {
	return getClass(className, false);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy