我在某处读到不可能在运行时获得类的通用接口。那么休眠是如何做到这一点的呢?例如在 OneToMany 映射中,hibernate 如何找出许多部分类(使用注释)?
class A{
    ...
    @OneToMany(mapped-by="a")
    public List<B> getBs(){ 
    ...
    }
}
我在某处读到不可能在运行时获得类的通用接口。那么休眠是如何做到这一点的呢?例如在 OneToMany 映射中,hibernate 如何找出许多部分类(使用注释)?
class A{
    ...
    @OneToMany(mapped-by="a")
    public List<B> getBs(){ 
    ...
    }
}
我在某处读到不可能在运行时获得类的通用接口。
这取决于。您不能询问泛型类型的实例其类型参数是什么 - 但您可以从有关类、方法返回类型等的元数据中获取该信息。
例如,Method.getGenericReturnType返回 aType而不是 a Class<?>,这样您就可以获取相关信息。
示例代码:
import java.lang.reflect.*;
import java.util.*;
public class Test {
    public static void main(String[] args) throws Exception {
        Method method = Test.class.getMethod("getList");
        Type returnType = method.getGenericReturnType();
        System.out.println(returnType); // java.util.List<java.lang.Integer>
        ParameterizedType parameterized = (ParameterizedType) returnType;
        System.out.println(parameterized.getActualTypeArguments()[0]);
    }    
    public List<Integer> getList() {
        return null;
    }
}
类包含存储一些通用信息的元数据。