I am looking for analogous implementation of the following in Java. This code in C++ is to call methods appropriately using function pointers, depending upon the input, avoiding the ugly if..else ladder. (Please except solution based on Polymorphism - basically creating new classes along with an interface that allows specific implementations. Also cannot use Java 8 (lambda) in my project).
Any alternative in Java?
#include "stdafx.h"
#include <map>
#include <iostream>
using namespace std;
class Func;
typedef void (Func::*FUNC_TYPE) ();
class Func
{
public:
Func()
{
fncMap[1] = &Func::fn1;
fncMap[2] = &Func::fn2;
fncMap[3] = &Func::fn3;
fncMap[4] = &Func::fn4;
}
void fn1(){ cout << "fn1" << endl; }
void fn2(){ cout << "fn2" << endl; }
void fn3(){ cout << "fn3" << endl; }
void fn4(){ cout << "fn4" << endl; }
map<int, FUNC_TYPE> fncMap;
};
void callAppropriateFunction (Func& Ob, int input)
{
auto itrFind = Ob.fncMap.find(input);
if (itrFind == Ob.fncMap.end()) return;
FUNC_TYPE fn = itrFind->second;
(Ob.*fn) ();
}
int _tmain(int argc, _TCHAR* argv[])
{
Func Ob;
int i;
cin >> i;
callAppropriateFunction(Ob, i);
return 0;
}