Re: simple method to simulate function pointers in java
Arne Vajh=F8j wrote:
Lino Ferrentino wrote:
Maybe there are other methods... I use this:
public final class b_callbacks {
private b_callbacks(){
}
public static interface void_f_void{
public void f();
}
public static interface void_f_int{
public void f(int i);
}
}
----
when I want to use a function pointer
import b_callbacks.void_f_int;
private void_f_int my_callback;
my_callback = new void_f_int(){
public void f(int i){
//code
}
};
to call the callback
my_callback.f(42);
====
For each function pointer type we create an interface.
It is perfectly valid.
You need to note two things:
1) the codes is not following Java coding convention
2) it is based on an assumption that all functions with
the same signature are interchangeable - that is not
very type safe
The Java idiom is to use a functor, typically a single-abstract-method (SAM=
) interface, and pass an instance of that functor type to the object needin=
g a callback or similar method. The object implementing the functor interf=
ace is the called-back object.
And as Arne says, do follow the coding conventions. Your code was nearly i=
mpenetrable. You name things by purpose in Java, not by implementation typ=
e.
Roughly (very roughly)_speaking, the functor pattern is something like:
public interface Updater
{
public void update( Information info );
}
============
public class SomethingThatUpdates
{
private final List <Updater> updaters = new ArrayList <> ();
public void addUpdater( Updater updater )
{
updaters.add( updater );
}
public void doUpdates()
{
Information info = obtainInformationSomehow();
for( Updater upd : updaters )
{
upd.update( info );
}
}
// etc.
}
============
public class SomethingToUpdate implements Updater
{
public void init( SomethingThatUpdates something )
{
something.addUpdater( this );
}
public void update( Information info )
{
// do something useful with 'info'
}
// etc.
}
============
--
Lew