如何投射 List能够调用各个对象的特定方法?
我对 List 的通用转换有一些想法,但老实说,我不知道是否可以实现。
我的应用程序中有这个代码片段
public String getObjectACombo() {
List<ObjectA> listA = theDAO.getObjectA();
String combo = getCombo(listA, "rootA"); // --> This line
}
public String getObjectBCombo() {
List<ObjectB> listB = theDAO.getObjectB();
String combo = getCombo(listA, "rootA"); // --> This line
}
首先,我正在为“-->此行”提到的行编写一些例程。但这两种方法具有完全相同的算法来从 List 生成 JSON 字符串。已从数据库返回。所以我想用通用方法 getCombo(List
public <T> String getCombo(List<T> list, String root) {
Iterator<T> listItr = list.iterator();
...
while ( listItr.hasNext() ) {
jsonObj.put(list.get(i).toJson()); // --> The Error line
}
}
错误发生在“错误行”。 ObjectA.java 和 ObjectB.java 中都有 toJson() 方法,但在上述行中“未定义类型 T 的方法 toJson()”。
我尝试用 (T) 和 Class.forName() 来转换它,但它们都不起作用。
有解决这个问题的方法吗?有可能吗?
I'm having something in my mind about generic casting for List, but honestly I don't know if it's possible to implement or not.
There is this code snippet in my application
public String getObjectACombo() {
List<ObjectA> listA = theDAO.getObjectA();
String combo = getCombo(listA, "rootA"); // --> This line
}
public String getObjectBCombo() {
List<ObjectB> listB = theDAO.getObjectB();
String combo = getCombo(listA, "rootA"); // --> This line
}
Firstly I was coding some routine for the lines mentioned as "--> This line". But the two methods have the exact same algorithm to generate JSON string from List<?> which has been returned from the database. So I am thinking to replace them with a generic method, getCombo(List<T> list, String root). But the thing is I couldn't mange to make it work.
public <T> String getCombo(List<T> list, String root) {
Iterator<T> listItr = list.iterator();
...
while ( listItr.hasNext() ) {
jsonObj.put(list.get(i).toJson()); // --> The Error line
}
}
The error happens of the "The Error line". Both ObjectA.java and ObjectB.java have the toJson() method in them, but "The method toJson() is undefined for the type T" at the mentioned line.
I tried to cast it with (T) and Class.forName(), but neither of them had worked.
Is there any work around to this problem? Is it even possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用定义
toJson()
方法的接口,例如Jsonable
:) - 然后限制T
:这样编译器就知道每个 < code>T 必须继承自
Jsonable
,因此具有toJson()
方法。编辑:这是我的意思的一个示例,使用已经存在的
Comparable
接口:Use an interface that defines the
toJson()
method, e.g.Jsonable
:) - and then restrictT
:This way the compiler knows that each
T
must inherit fromJsonable
and thus has thetoJson()
method.Edit: here's an example of what I mean, using the already existing
Comparable<T>
interface:尝试对每个使用 a :
Try to use a for each: