1、java 如何获取接口中定义的泛型的实际类型

经过研究后今天给出一个小例子

package test;

import java.lang.annotation.*;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

// 注解
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
 @interface Table {
    String tableName();
    String primaryKey() default "";
}
// 实体类
@Table(tableName = "m_person")
class Person{
}
// 通用 缓存
interface MyCash<T>{
    void removeCacheById(Object id);
}
// 业务接口
interface PersonService<T> extends MyCash<T>{

}
// 业务接口实现
class PersonServiceImpl implements PersonService<Person>{
    @Override
    public void removeCacheById(Object id) {
        //@@删除缓存
    }
}

public class SanUser {

    public static void getInfo(MyCash myCash) throws ClassNotFoundException {
        Type[] genericInterfaces = myCash.getClass().getGenericInterfaces();
        for (Type t : genericInterfaces) {
            Type[] genericType2 = ((ParameterizedType) t).getActualTypeArguments();
            for (Type t2 : genericType2) {
                String className = t2.getTypeName();// 接口中定义的泛型className
                System.out.println(className);
                // 获取泛型类型上的主键,并获取注解上的tableName
                Table annotation = Class.forName(className).getAnnotation(Table.class);
                String s = annotation.tableName();
                // 打印泛型注解
                System.out.println(s);
            }
        }
    }
    public static void main(String[] args) throws ClassNotFoundException {
        MyCash myCash = new PersonServiceImpl();
        getInfo(myCash);
    }
}
最后修改于 2020-02-13 11:38:09
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付
上一篇