gpt4 book ai didi

java - 在java中获取通用接口(interface)

转载 作者:行者123 更新时间:2023-11-30 07:23:32 25 4
gpt4 key购买 nike

我在某处读到,不可能在运行时获得类的通用接口(interface)。那么hibernate是如何做到这一点的呢?例如在 OneToMany 映射中,hibernate 如何找到 Many 部分类(使用注释)?

class A{
...
@OneToMany(mapped-by="a")
public List<B> getBs(){
...
}
}

最佳答案

I read somewhere that it's impossible to get generic interface of a class in run time.

这取决于。您无法询问泛型类型的实例其类型参数是什么 - 但您可以从有关类、方法返回类型等的元数据中获取该信息。

例如, Method.getGenericReturnType 返回 Type而不是 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;
}
}

关于java - 在java中获取通用接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11977848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com