问题
这可能是常见和微不足道的事情,但我似乎无法找到具体的答案。在C#中有一个委托的概念,它强烈地与C的函数指针的想法有关。 Java中是否有类似的功能?鉴于指针有点缺席,最好的方法是什么?要说清楚,我们在这里谈论头等舱。
#1 热门回答(115 赞)
类似于函数指针的功能的Java习语是实现接口的匿名类,例如,
Collections.sort(list, new Comparator<MyClass>(){
public int compare(MyClass a, MyClass b)
{
// compare objects
}
});
**更新:**以上在Java 8之前的Java版本中是必需的。现在我们有更好的替代方案,即lambdas:
list.sort((a, b) -> a.isGreaterThan(b));
和方法参考:
list.sort(MyClass::isGreaterThan);
#2 热门回答(62 赞)
你可以使用接口替换函数指针。假设你想要运行一个集合并对每个元素做一些事情。
public interface IFunction {
public void execute(Object o);
}
这是我们可以传递给CollectionUtils2.doFunc(Collection c,IFunction f)的接口。
public static void doFunc(Collection c, IFunction f) {
for (Object o : c) {
f.execute(o);
}
}
举个例子说我们有一个数字集合,你想为每个元素添加1。
CollectionUtils2.doFunc(List numbers, new IFunction() {
public void execute(Object o) {
Integer anInt = (Integer) o;
anInt++;
}
});
#3 热门回答(41 赞)
你可以使用反射来做到这一点。
将参数作为参数传递给对象和方法名称(作为字符串),然后调用该方法。例如:
Object methodCaller(Object theObject, String methodName) {
return theObject.getClass().getMethod(methodName).invoke(theObject);
// Catch the exceptions
}
然后使用它,如:
String theDescription = methodCaller(object1, "toString");
Class theClass = methodCaller(object2, "getClass");
当然,检查所有异常并添加所需的强制转换。