Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Calling a function by vairable

Status
Not open for further replies.

EdGioja

Programmer
Nov 6, 2003
39
US
I've been looking, so if the answer is in the documents somewhere, I would be happy with a link.

Here's the situation:

I have a progam with LOTS of functions. I have a controlling function that reads in a string variable. This variable contains the names of functions and parameters:

func1(a,b,c);func2;func3(a,b,c)

I have functions that correspond to these function calls.
I don't really want to write a big IF statement...I would rather parse the string so that I have a variable called strFuncName.

strFuncName = "func1"
strParams = "a,b,c"

Now, I want to call func1(a,b,c), then call func2, then func3(a,b,c). I also want to gracefully handle the exception if a function is called that doesn't actually exist.

Any ideas?

Thank you.
 
I need to rephrase this:

strFuncName = "func1"
strParams = "a,b,c"
Now, I want to call func1(a,b,c), then call func2, then func3(a,b,c). I also want to gracefully handle the exception if a function is called that doesn't actually exist.



I want to call:
strFuncName(strParams) without knowing specifically what it is.
 
Thank you. Thank you, also, for not saying "RTFM." I tried that (3 of them), and wasn't getting anywhere.
glasses.gif
 
That's the way to do it, but I don't think it's the answer.

The answer is that Java is not an scripting language like Javascript, it's an OO language and, even if you can do things like this, it's not a good practice, it usually means you have a bad design in your application.

Cheers,
Dian
 
Hi

Works for me.
Code:
[highlight antiquewhite]   CallTheFunc.java          [/highlight]
import java.lang.reflect.*;

public class CallTheFunc
{
    public void doCall()
    {
        String strFuncName="func1";
        String strParams="a,b,c";
        
        String[] piece=strParams.split(",");
        Class[] param=new Class[piece.length];
        for (int i=0;i<piece.length;i++) param[i]=piece[i].getClass();
        
        Method callIt=null;
        
        try {
            callIt=Unknown.class.getMethod(strFuncName,param);
        } catch (NoSuchMethodException e) {
            System.out.println("error : can not get");
            return;
        }

        try {
            callIt.invoke(new Unknown(),piece);
        } catch (IllegalAccessException e) {
            System.out.println("error : can not call");
        } catch (InvocationTargetException e) {
            System.out.println("error : can not call");
        }
         
    }
}



[highlight antiquewhite]   Unknown.java          [/highlight]
public class Unknown
{
    public void func1(String a,String b,String c)
    {
        System.out.println("called with '"+a+"', '"+b+"' and '"+c+"'");
    }
}
output said:
called with 'a', 'b' and 'c'

Feherke.
 
Whenever you find yourself using varaibles to hold the names of other variables or functions, it nearly always means your design is going down the wrong path.

You may be better off looking at the Command pattern, or if your requirements for interpreting the 'script' are more complex, the Interpreter pattern.

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
I don't think there is much of a problem with reflection to be fair. It can be extremely useful sometimes.

Some big projects our there use it all the time, such as Apache Axis ...

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Appart from a factory, I can't see a reason to use reflection appart from a bad design.

Cheers,
Dian
 
I'd go with Dian's opinion. Reflection is brilliant if you are writing a debugger, IDE, or a tool like JUnit. If you aren't it can add unnecessary complication to your code, and has a nasty habit of moving problems from compile-time to run-time, where they are harder to track down.

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top