gpt4 book ai didi

java - 使用 Java 泛型从类名获取类型

转载 作者:行者123 更新时间:2023-12-03 02:49:27 25 4
gpt4 key购买 nike

我有以下类,我需要在构造函数中获取类型,我该怎么做?

public abstract class MyClass<T> {
public MyClass()
{
// I need T type here ...
}
}

编辑:

这是我想要实现的具体示例:

public abstract class Dao<T> {
public void save(GoogleAppEngineEntity entity)
{
// save entity to datastore here
}

public GoogleAppEngineEntity getEntityById(Long id)
{
// return entity of class T, how can I do that ??
}
}

我想要做的是将此类扩展到所有其他 DAO,因为其他 DAO 有一些特定于这些 dao 的查询,不能通用,但这些简单的查询应该普遍适用于所有 DAO 接口(interface)/实现...

最佳答案

在某种程度上,你可以得到它......不确定这是否有用:

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

abstract class MyClass<T> {
public MyClass() {
Type genericSuperclass = this.getClass().getGenericSuperclass();
if (genericSuperclass instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) genericSuperclass;
Type type = pt.getActualTypeArguments()[0];
System.out.println(type); // prints class java.lang.String for FooClass
}
}
}

public class FooClass extends MyClass<String> {
public FooClass() {
super();
}
public static void main(String[] args) {
new FooClass();
}
}

关于java - 使用 Java 泛型从类名获取类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2969712/

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