java 获取泛型类的Class对象

1、范型工具类

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class GenericSuperclassUtil {

    public static Class getActualTypeArgument(Class clazz) {
        Class entitiClass = null;
        Type genericSuperclass = clazz.getGenericSuperclass();
        if (genericSuperclass instanceof ParameterizedType) {
            Type[] actualTypeArguments = ((ParameterizedType) genericSuperclass)
                    .getActualTypeArguments();
            if (actualTypeArguments != null && actualTypeArguments.length > 0) {
                entitiClass = (Class) actualTypeArguments[0];
            }
        }
        return entitiClass;
    }

    public static Class getActualTypeArgument(Class clazz,int i) {
        Class entitiClass = null;
        Type genericSuperclass = clazz.getGenericSuperclass();
        if (genericSuperclass instanceof ParameterizedType) {
            Type[] actualTypeArguments = ((ParameterizedType) genericSuperclass)
                    .getActualTypeArguments();
            if (actualTypeArguments != null && actualTypeArguments.length > 0) {
                entitiClass = (Class) actualTypeArguments[i];
            }
        }
        return entitiClass;
    }


}

2、通用Service


import com.baomidou.mybatisplus.extension.service.IService;

public interface BaseService extends IService {
}

3、具体实现

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class BaseServiceImpl, ENTITY> extends ServiceImpl implements BaseService {


    protected Class getEntityClass() {
        return (Class) GenericSuperclassUtil.getActualTypeArgument(this.getClass(),1);
    }

    protected Class getMapperClass(){
        return (Class) GenericSuperclassUtil.getActualTypeArgument(this.getClass(),0);
    }






}

你可能感兴趣的:(java,开发语言,范型)