net.ymate.platform.core.util.ClassUtils.java Source code

Java tutorial

Introduction

Here is the source code for net.ymate.platform.core.util.ClassUtils.java

Source

/*
 * Copyright 2007-2016 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 net.ymate.platform.core.util;

import com.thoughtworks.paranamer.AdaptiveParanamer;
import net.ymate.platform.core.lang.BlurObject;
import net.ymate.platform.core.lang.PairObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;

/**
 * ?
 *
 * @author  (suninformation@163.com) on 2012-12-5 ?6:41:23
 * @version 1.0
 */
public class ClassUtils {

    private static final Log _LOG = LogFactory.getLog(ClassUtils.class);

    private static InnerClassLoader _INNER_CLASS_LOADER = new InnerClassLoader(new URL[] {},
            ClassUtils.class.getClassLoader());

    public static class InnerClassLoader extends URLClassLoader {

        public InnerClassLoader(URL[] urls, ClassLoader parent) {
            super(urls, parent);
        }

        @Override
        public void addURL(URL url) {
            super.addURL(url);
        }

    }

    /**
     * @return 
     */
    public static ClassLoader getDefaultClassLoader() {
        return _INNER_CLASS_LOADER;
    }

    /**
     * ?????
     *
     * @param <T>            ?
     * @param className      ??
     * @param interfaceClass ????
     * @param callingClass   
     * @return ???
     */
    @SuppressWarnings("unchecked")
    public static <T> T impl(String className, Class<T> interfaceClass, Class<?> callingClass) {
        if (StringUtils.isNotBlank(className)) {
            try {
                Class<?> implClass = loadClass(className, callingClass);
                if (interfaceClass == null || interfaceClass.isAssignableFrom(implClass)) {
                    return (T) implClass.newInstance();
                }
            } catch (Exception e) {
                _LOG.warn("", RuntimeUtils.unwrapThrow(e));
            }
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    public static <T> T impl(Class<?> implClass, Class<T> interfaceClass) {
        if (implClass != null) {
            if (interfaceClass == null || interfaceClass.isAssignableFrom(implClass)) {
                try {
                    return (T) implClass.newInstance();
                } catch (Exception e) {
                    _LOG.warn("", RuntimeUtils.unwrapThrow(e));
                }
            }
        }
        return null;
    }

    public static Class<?> loadClass(String className, Class<?> callingClass) throws ClassNotFoundException {
        Class<?> _targetClass = null;
        try {
            _targetClass = Thread.currentThread().getContextClassLoader().loadClass(className);
        } catch (ClassNotFoundException e) {
            try {
                _targetClass = Class.forName(className, false, ClassUtils.class.getClassLoader());
            } catch (ClassNotFoundException ex) {
                try {
                    _targetClass = _INNER_CLASS_LOADER.loadClass(className);
                } catch (ClassNotFoundException exc) {
                    _targetClass = callingClass.getClassLoader().loadClass(className);
                }
            }
        }
        return _targetClass;
    }

    /**
     * @param clazz      
     * @param superClass 
     * @return clazz?superClass?
     */
    public static boolean isSubclassOf(Class<?> clazz, Class<?> superClass) {
        boolean _flag = false;
        do {
            Class<?> cc = clazz.getSuperclass();
            if (cc != null) {
                if (cc.equals(superClass)) {
                    _flag = true;
                    break;
                } else {
                    clazz = clazz.getSuperclass();
                }
            } else {
                break;
            }
        } while ((clazz != null && clazz != Object.class));
        return _flag;
    }

    /**
     * @param clazz          
     * @param interfaceClass ?
     * @return clazz?interfaceClass?
     */
    public static boolean isInterfaceOf(Class<?> clazz, Class<?> interfaceClass) {
        boolean _flag = false;
        do {
            for (Class<?> cc : clazz.getInterfaces()) {
                if (cc.equals(interfaceClass)) {
                    _flag = true;
                }
            }
            clazz = clazz.getSuperclass();
        } while (!_flag && (clazz != null && clazz != Object.class));
        return _flag;
    }

    /**
     * @param target          ??Field?MethodClass
     * @param annotationClass 
     * @return target?annotationClass
     */
    public static boolean isAnnotationOf(Object target, Class<? extends Annotation> annotationClass) {
        if (target instanceof Field) {
            if (((Field) target).isAnnotationPresent(annotationClass)) {
                return true;
            }
        } else if (target instanceof Method) {
            if (((Method) target).isAnnotationPresent(annotationClass)) {
                return true;
            }
        } else if (target instanceof Class) {
            if (((Class<?>) target).isAnnotationPresent(annotationClass)) {
                return true;
            }
        }
        return false;
    }

    /**
     * @param clazz 
     * @return ????
     */
    public static String[] getInterfaceNames(Class<?> clazz) {
        Class<?>[] interfaces = clazz.getInterfaces();
        List<String> names = new ArrayList<String>();
        for (Class<?> i : interfaces) {
            names.add(i.getName());
        }
        return names.toArray(new String[names.size()]);
    }

    /**
     * @param clazz 
     * @return ????, ??RawType
     */
    public static List<Class<?>> getParameterizedTypes(Class<?> clazz) {
        List<Class<?>> _clazzs = new ArrayList<Class<?>>();
        Type _types = clazz.getGenericSuperclass();
        if (ParameterizedType.class.isAssignableFrom(_types.getClass())) {
            for (Type _type : ((ParameterizedType) _types).getActualTypeArguments()) {
                if (ParameterizedType.class.isAssignableFrom(_type.getClass())) {
                    _clazzs.add((Class<?>) ((ParameterizedType) _type).getRawType());
                } else {
                    _clazzs.add((Class<?>) _type);
                }
            }
        } else {
            _clazzs.add((Class<?>) _types);
        }
        return _clazzs;
    }

    /**
     * ?clazzField?
     *
     * @param clazz  
     * @param parent ??
     * @return Field?
     */
    public static List<Field> getFields(Class<?> clazz, boolean parent) {
        List<Field> fieldList = new ArrayList<Field>();
        Class<?> clazzin = clazz;
        do {
            if (clazzin == null) {
                break;
            }
            fieldList.addAll(Arrays.asList(clazzin.getDeclaredFields()));
            if (parent) {
                clazzin = clazzin.getSuperclass();
            } else {
                clazzin = null;
            }
        } while (true);
        return fieldList;
    }

    /**
     * @param <A>             
     * @param clazz           
     * @param annotationClazz 
     * @return ?clazz?annotationClazz
     */
    public static <A extends Annotation> List<PairObject<Field, A>> getFieldAnnotations(Class<?> clazz,
            Class<A> annotationClazz) {
        List<PairObject<Field, A>> _annotations = new ArrayList<PairObject<Field, A>>();
        for (Field _field : ClassUtils.getFields(clazz, true)) {
            A _annotation = _field.getAnnotation(annotationClazz);
            if (_annotation != null) {
                _annotations.add(new PairObject<Field, A>(_field, _annotation));
            }
        }
        return _annotations;
    }

    /**
     * @param <A>             
     * @param clazz           
     * @param annotationClazz 
     * @return ?clazz?annotationClazz
     */
    public static <A extends Annotation> PairObject<Field, A> getFieldAnnotationFirst(Class<?> clazz,
            Class<A> annotationClazz) {
        PairObject<Field, A> _returnAnno = null;
        for (Field _field : ClassUtils.getFields(clazz, true)) {
            A _annotation = _field.getAnnotation(annotationClazz);
            if (_annotation != null) {
                _returnAnno = new PairObject<Field, A>(_field, _annotation);
                break;
            }
        }
        return _returnAnno;
    }

    /**
     * @param method 
     * @return ????
     */
    public static String[] getMethodParamNames(final Method method) {
        return new AdaptiveParanamer().lookupParameterNames(method);
    }

    /**
     * @param clazz 
     * @return 
     */
    public static Class<?> getArrayClassType(Class<?> clazz) {
        try {
            return Class.forName(StringUtils.substringBetween(clazz.getName(), "[L", ";"));
        } catch (ClassNotFoundException e) {
            _LOG.warn("", RuntimeUtils.unwrapThrow(e));
        }
        return null;
    }

    /**
     * @param <T>   
     * @param clazz 
     * @return ???
     */
    public static <T> BeanWrapper<T> wrapper(Class<T> clazz) {
        try {
            return wrapper(clazz.newInstance());
        } catch (Exception e) {
            _LOG.warn("", RuntimeUtils.unwrapThrow(e));
        }
        return null;
    }

    /**
     * @param <T>    
     * @param target 
     * @return ???
     */
    public static <T> BeanWrapper<T> wrapper(T target) {
        return new BeanWrapper<T>(target);
    }

    /**
     * ??
     *
     * @author  (suninformation@163.com) on 2012-12-23 ?12:46:50
     * @version 1.0
     */
    public static class BeanWrapper<T> {

        private T target;

        private Map<String, Field> _fields;

        protected BeanWrapper(T target) {
            this.target = target;
            this._fields = new LinkedHashMap<String, Field>();
            //
            for (Field _field : getFields(target.getClass(), true)/*target.getClass().getDeclaredFields()*/) {
                if (Modifier.isStatic(_field.getModifiers())) {
                    // ???
                    continue;
                }
                _field.setAccessible(true);
                this._fields.put(_field.getName(), _field);
            }
        }

        public T getTargetObject() {
            return target;
        }

        public Set<String> getFieldNames() {
            return _fields.keySet();
        }

        public Annotation[] getFieldAnnotations(String fieldName) {
            return _fields.get(fieldName).getAnnotations();
        }

        public Field getField(String fieldName) {
            return _fields.get(fieldName);
        }

        public Class<?> getFieldType(String fieldName) {
            return _fields.get(fieldName).getType();
        }

        public BeanWrapper<T> setValue(String fieldName, Object value) throws IllegalAccessException {
            _fields.get(fieldName).set(target, value);
            return this;
        }

        public Object getValue(String fieldName) throws IllegalAccessException {
            return _fields.get(fieldName).get(target);
        }

        public BeanWrapper<T> fromMap(Map<String, Object> map) {
            for (Map.Entry<String, Object> _entry : map.entrySet()) {
                try {
                    setValue(_entry.getKey(), _entry.getValue());
                } catch (Exception ignored) {
                    // ??
                }
            }
            return this;
        }

        public Map<String, Object> toMap() {
            Map<String, Object> _returnValues = new HashMap<String, Object>();
            for (Field _field : _fields.values()) {
                try {
                    _returnValues.put(_field.getName(), getValue(_field.getName()));
                } catch (Exception ignored) {
                    // ??
                }
            }
            return _returnValues;
        }

        /**
         * @param dist 
         * @param <D>  
         * @return ???
         */
        public <D> D duplicate(D dist) {
            BeanWrapper<D> _wrapDist = wrapper(dist);
            for (String _fieldName : getFieldNames()) {
                if (_wrapDist.getFieldNames().contains(_fieldName)) {
                    Object _fValue = null;
                    try {
                        _fValue = getValue(_fieldName);
                        _wrapDist.setValue(_fieldName, _fValue);
                    } catch (Exception e) {
                        // ?????NULL??
                        if (_fValue != null) {
                            try {
                                _wrapDist.setValue(_fieldName,
                                        BlurObject.bind(_fValue).toObjectValue(_wrapDist.getFieldType(_fieldName)));
                            } catch (Exception ignored) {
                                // ?????
                            }
                        }
                    }
                }
            }
            return _wrapDist.getTargetObject();
        }

    }

}