开发者

What is the cloest thing to a function pointer in java? [duplicate]

开发者 https://www.devze.com 2023-02-04 11:24 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: What's the nearest substitute for a function pointer in Java?
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

What's the nearest substitute for a function pointer in Java?

I just have a situation where it would be nice to have the functionality of something similar to function pointers like you might use in c or c++. The best thing I can think of is combinin开发者_运维问答g Runnables and launch them in a different thread. Suggestions?


Until they add closures to java, the thing seems closest to java.lang.reflect.Method. For example Method method = SomeClass.getMethod("methodName", methodParameterTypes)

Then you can pass the method around (like a function pointer) and call invoke(..) on it, passing an object (or null if static)

But this is not quite a good practice. You can define an interface, or use an existing one Runnable / Callable, implement it inline, and pass the instance.


Use Functors, aka Function Objects.

Java has no first-class functions, so function objects are usually expressed by an interface with a single method (most commonly the Callable interface), typically with the implementation being an anonymous inner class.


You might be looking for the command pattern, which essentially defines an interface with one method (say execute()) and classes implementing this method for different actions. You can use references to instances of these classes kinda like function pointers in C++. This pattern is often used to implement interpreters.


One option is using java.lang.reflect.Method, as explained in Bozho's answers. It's very flexible, but the main drawbacks are that you lose all type safety - there is no check that you are calling the method with the right parameters (and expect the right return type).

So if you later change the method, and forget to change all callers, you'll only find out at runtime (through a ClassCastException). Even the method name is only checked at runtime (because you fetch it by name.

An alternative is to use callbacks via interfaces. A method that wants to accept another method as a parameter just expects an instance of a certain interface. The interface only has one method, doStuff. Then you can create instances that implement the interface, and pass those to the methods. That's a bit more verbose (because you need the interface), but typesafe and thus easier to refactor.

That is more or less the command pattern, BTW.


Callbacks are a way to implement something similar what you do with a function pointer in C++.
Additionally they are type-safe (unlike function pointers which might not be).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号