gpt4 book ai didi

Java如何避免将Class作为泛型对象的参数传递

转载 作者:行者123 更新时间:2023-11-29 08:26:04 25 4
gpt4 key购买 nike

我写了以下内容:

public class DataContainer<Data>{

public DataContainer(Class<Data> clazz, String method) throws NoSuchMethodException, SecurityException{

clazz.getMethod(method);

}

}

所以我这样创建我的对象:

new DataContainer<SomeClass>(SomeClass.class, "get");

但我希望它看起来更像:

public class DataContainer<Data>{

public DataContainer(String method) throws NoSuchMethodException, SecurityException{

Data.getMethod(method);

}

}

构造调用应该如下所示:

new DataContainer<SomeClass>("get");

如何避免通过 Data我构造 A 时的类 DataContainer目的?我知道Data无法在运行时进行操作(new DataContainer<>("get"); -> 什么是数据?)但我听说有解决方案可以解决,不幸的是我似乎还没有词汇来谷歌它。

这也是我的问题的简化版本,我们假设方法是有效的、公开的并且没有参数。

最佳答案

由于类型删除,您想要使用代码的方式实际上是不可能的。

然而,一些通用信息在运行时被保留,即当它可以被反射访问时。一种这样的情况是类层次结构上的泛型,即你可以做这样的事情(我们经常这样做):

//Note that I used T instead of Data to reduce confusion
//Data looks a lot like an actual class name
public abstract class DataContainer<T>{
public DataContainer(String method) throws NoSuchMethodException, SecurityException {
Class<?> actualClass = getActualTypeForT();
//use reflection to get the method from actualClass and call it
}

protected Class<?> getActualTypeForT() {
//get the generic boundary here, for details check http://www.artima.com/weblogs/viewpost.jsp?thread=208860
}
}

//A concrete subclass to provide the actual type of T for reflection, can be mostly empty
public class SomeClassContainer extends DataContainer<SomeClass> {
//constructor etc.
}

虽然我没有测试过,但类字段或参数应该也有类似的东西。

关于Java如何避免将Class作为泛型对象的参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53008658/

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