【发布时间】:2022-11-30 16:07:41
【问题描述】:
我有来自不同类的一些项目,我想编写一个采用通用对象的方法(目的是所有其他类的超类)
- 验证项目都有 getId() 方法
- 然后收集 getId() 值。
请注意,对象实际上可以是任何东西——它不能被限制
我试过类似的东西
String getObjectId(Object item) throws Exception {
// If the getId() method is not implemented, throw exception
if (Arrays.stream(item.getClass().getMethods())
.filter(method -> "getId".equals(method.getName()))
.findFirst()
.isEmpty()) {
throw new Exception(...);
}
return item.getId();
}
问题是编译器忽略了这个验证——我总是得到这个错误,即使我只是验证它有方法
cannot find symbol
return item.getId();
^
在这种情况下如何调用方法?
【问题讨论】:
-
您是否检查过 Object 类是否具有“getId()”方法?您的返回语句不会通过 getClass() 和所有这些。它只是在 Object 类中寻找该方法,因为这就是声明的项目
-
正确的方法是使用强制存在 getId() 的接口。
-
你不能像这样在
Object上调用item.getId()。如果您使用反射,则需要使用Method.invoke(item)来调用您找到的方法。但是反射在这里似乎不是一个好的解决方案,你不能为那些暴露getId()方法的类添加一个通用接口吗?这样一来,您可能一开始就不需要getObjectId()方法。 -
我相信它不是developer.classpath.org/doc/java/lang/Object-source.html 嗯,这是一个很好的观点。也许我可以通过 Object 中存在的身份函数重命名 getId()
-
这回答了你的问题了吗? How do I call a method of a generic type object?