- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我有一个类有两个这样的方法:
public class Dummy{
public void doIt(String arg1, File arg2, Writer... ctx){
// Do something very important...
}
public void doIt(String arg1, Writer... ctx){
// Do something else...
}
public static void main(String[] args){
new Dummy().doIt("Test", null);
}
}
我预计编译器会报错,因为方法调用不明确。而是调用第二种方法。
在我们的例子中,模棱两可的方法是从数据库方法和稍后添加的可变参数生成的。现在我们不知道如何避免示例中的方法调用问题。
有没有其他人有这个问题以及如何解决它的想法?
最佳答案
我是这样给出答案的:
The problem is how to find method calls like this, where the first method should be called (and was before we changed our code generator), but the second one is called.
首先,正如已经指出的那样,Java 编译器会给出有关此类方法用法的警告。它看起来像这样:
com/stack/undsprlbl/varargs/Main.java:10: warning: non-varargs call of varargs method with inexact argument type for last parameter;
并且可以很容易地从 javac
输出中进行 grep
编辑。
其次,您可以考虑按照以下几行为您的代码编写一些自测试:
Class cl = Ambiguity.class;
Method[] methods = cl.getDeclaredMethods();
Set<String> varargsMethods = new HashSet<String>();
for (Method method : methods) {
Class c[] = method.getParameterTypes();
if(c.length > 0)
{
Class last = c[c.length - 1];
if(last.isArray())
{
if(varargsMethods.contains(method.getName()))
System.out.println("Method " + cl.getName() + "#"+ method.getName() + " looks suspicious.");
else
varargsMethods.add(method.getName());
}
}
}
了解您应该遍历所有类而不是直接提及。这answer似乎是一种方法---获取应用程序中的所有包并检查它们。
此时您将有两个列表:
不明确的可变参数方法用法列表
不明确的可变参数方法列表。
通过交叉这两个,您可以找出您可能会遇到问题的地方。
接下来,我建议在添加第二种方法之前检查代码的版本,并找出第一种方法的所有用法。显然必须消除歧义,以支持 HEAD 版本中的第一种方法。这样一来,我想,剩下的调用数量将非常有限。
关于使用 varargs 的方法不明确的 Java Bug?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21633766/
我在 linux 上工作。我对windows没有太多想法。 windows中文件的权限是如何组织的?我们在unix中是否有像chmod这样的api来更改权限? 最佳答案 对于 Windows,有一个名
应用程序编程接口(interface) (API) 是一组用于访问基于 Web 的软件应用程序的编程指令和标准。 如果出现 ,有人可以向我解释一下吗?谷歌地图 或 优酷 这是API哪个是softwar
我有两个应用程序,A 和 B,它们使用 android 库 C。B 有一个服务 A 想通过 C 使用,例如 在我的库中有一个类试图将它绑定(bind)到服务,
我正在正常或安全模式下启动相机应用程序,具体取决于使用我的应用程序执行的手势,但一旦用户选择应用程序并点击始终,则没有选项可以更改默认值,即使是从 Android 的设置菜单中也是如此. camera
我有一个数据集,本质上是一个稀疏二进制矩阵,表示两个集合的元素之间的关系。例如,让第一组是人(用他们的名字表示),例如像这样的东西: people = set(['john','jane','mike
何为pythonic? pythonic如果翻译成中文的话就是很python。很+名词结构的用法在中国不少,比如:很娘,很国足,很CCTV等等。 我的理解为,很+名词表达了一种特殊和强调的意味。
某些 Prolog 目标的确定性成功问题已经一次又一次地出现在 - 至少 - 以下问题: Reification of term equality/inequality Intersection an
我指的是 DateTime.TryParse(string s, out DateTime result) 重载,它尝试从字符串中解析 DateTime - 没有特定的格式正在指定。 我可以从http
2020 年 04 月 10 日,《中共中央国务院关于构建更加完善的要素市场化配置体制机制的意见》正式公布,将数据确立为五大生产要素(土地、资本、劳动力以及技术)之
有人可以解释一下 NSNotification 的 addObserver 函数中 notificationSender 的用途吗? 这是 Apple 文档的解释: notificationSende
我是一名优秀的程序员,十分优秀!