gpt4 book ai didi

java - 泛型 : getting parameterizedtype classname from a static method?

转载 作者:行者123 更新时间:2023-12-01 07:40:10 24 4
gpt4 key购买 nike

我有一个简单的静态方法:

public static <U> U findStuff(String id) {
// how can i get the class of type U here ?
Class classObject = ....;

return classObject.newInstance();
}

public static void main(String[] args) {
MyEntity entity = MyClass.<MyEntity>findStuff("abc");
}

我想知道如何从 U 获取类对象?

目前我必须传递类(class),因为我还不知道路..所以,现在我使用这样的东西:

public static <U> U findStuff(Class<U> classObject, String id) {
return classObject.newInstance();
}

public static void main(String[] args) {
MyEntity entity = MyClass.findStuff(MyEntity.class, "abc");
}

最佳答案

要获取对象的类,请使用object.getClass();

顺便说一下,这是一种与泛型无关的常见方法

关于java - 泛型 : getting parameterizedtype classname from a static method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6015360/

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