JSmith said:
IMHO, the closest you can 'functionally' get to C-like function pointers in
Java is using an array of indexed command objects that all implement from an
interface/extend an abstract class.
Of course you will have to customize each object type behavoirs based on
its index ...
No silly switch statements and similar conditional ones
They have told you about strategies that 'syntactically look like' C-like
function pointers, but in reallity Java was deviced by design, among may
other things, to avoid exactly what you are looking for
IMHO, while syntactically a java app will not resemble a c app, one can
easily replicate function call backs in Java. Example follows.
// File: jCallbacks.java
import java.lang.Class;
import java.lang.Exception;
import java.lang.reflect.Method;
abstract class CallBackObject extends Exception
{
private Object cbObject = null;
private Method cbMethod = null;
private Object[] cbArgs = null;
protected CallBackObject() {};
protected CallBackObject(Object cbo,String cbmname,Class[] cbp)
throws Exception
{
setCallBackObject(cbo);
setCallBackMethod(cbmname,cbp);
}
protected void setCallBackObject(Object cbo)
throws Exception
{
cbObject = cbo;
}
protected void setCallBackMethod(String cbmname,Class[] cbp)
throws Exception
{
cbMethod = cbObject.getClass().getMethod(cbmname,cbp);
}
protected void setCallBackArgs(Object[] args)
throws Exception
{
cbArgs = args;
}
public void doCallBack() throws Exception
{
cbMethod.invoke(cbObject,cbArgs);
}
public void doCallBack(Object[] args) throws Exception
{
cbMethod.invoke(cbObject,args);
}
}
// CbExample could be an Observer of Inventory changes.
class CbExample extends CallBackObject
{
private String descr = null;
private Float price = null;
private Integer stock = null;
public CbExample(String what)
{
descr = what;
}
public void monitor() { monitor(descr); }
private void monitor(String what)
{
// Key into DB
descr = what;
// Observed event triggered, envision data from DB
price = new Float(9.99);
stock = new Integer(3);
try {
setCallBackArgs(new Object[] {descr,price,stock});
doCallBack();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
public class jCallbacks extends Exception
{
public static jCallbacks main = new jCallbacks();
public CbExample trigger = null;
public static void main(String[] args) throws Exception
{
main.begin();
}
public void begin() throws Exception
{
trigger = new CbExample("Widgets");
trigger.setCallBackObject(this);
trigger.setCallBackMethod("callBackHere",
new Class[] {String.class,Float.class,Integer.class});
trigger.monitor();
}
public void callBackHere(String desc,Float amount,Integer quantity)
{
Float total = new Float(quantity.intValue() * amount.floatValue());
System.out.println(desc + " for " + amount + " each, total " +
total);
}
}
joseph